As of Laravel 8 there has been introduction of Sanctum which has made APi authentication very easy. Here first I will explain about making Api authentication with Laravel and then I will inetgrate it with NuxtJs on frontend for the second part.
At first lets install a fresh copy of Laravel
Laravel Installation
laravel new nuxtapi
I guess you already know how to run a migration. For api lets directly go to api.php. As of the latest version Sanctum is already installed from the start.
Database Migration for Users
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Make an AuthController
php artisan make:controller AuthController
Auth Routes
api.php
Route::middleware(['prefix', 'auth'])->group(function () {
//User Registration
Route::post('register',AuthController::class,'register');
});
Here we will register username,email and password both username and email are unique.
Then run
Create a request for validation registration fields
php artisan make:request RegisterRequest
In app/HTTP/Requests/RegisterRequest.php
public function authorize()
{return true;}
public function rules()
{
return [
'username' => ['required', 'max:255', 'unique:users'],
'email' => ['required', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'max:255', 'unique:users', 'confirmed']
];
}
User Model User.php
In User Model you need to do mass assignment
protected $fillable = [
'username',
'email',
'password',
];
AuthController
public function register(RegisterRequest $request)
{
User::create($request->validated());
}
Testing Registration in Postman
We see we get all validation errors
When everything inserted correctly we get this confirmation
message.
Login
AuthController.php
In api.php
Route for login in api.php
Route::post('login', [AuthController::class, 'login']);
We will create a LoginRequest php artisan make:request LoginRequest
In app/HTTP/Requests/LoginRequest.php
LoginRequest.php
public function authorize()
{return true;}
public function rules()
{
return [
'email' => ['required', 'email', 'max:255'],
'password' => ['required', 'max:255']
];
}
public function login(LoginRequest $request)
{
if(!auth()->attempt($request->only('email', 'password'))){
throw new AuthenticationException("Email or password is not valid");
}
$token = auth()->user()->createToken('user-token');
return [
'message' => ['successfully logged in'],
'token' => $token->plainTextToken
];
}
For getting authenticated user
public function user()
{
return auth()->user();
}
We see when we enter nothing it gives us validation errors
When email and password generated successfully we get a token. This token is used for authorization
Logout
Route for logout
api.php
Route::post('logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
It will be inisde group auth
public function logout()
{
auth()->user()->currentAccessToken()->delete();
return [
'message'=>'Successfully Logged out'
];
}
Testing Logout in PostMan
It shows unauthenticated without token
With Token you can successfully logout
After you logout your token will expire
Test authorization with token
If you want that your customers cant enter specific route without token that is they are not authorizaed to neter that route.
That specific route
Postman Testing
If you try to access this route without token it will say give you a message of unauthenticated.
We are very much done with Laravel api authentication registration,login and logout.In the next part blog we will mention about how to intergrate it on frontend with Nuxt.js
Top comments (2)
thank u so much this is really helpful
You are welcome