DEV Community

Tanzim Ibthesam
Tanzim Ibthesam

Posted on • Updated on

Laravel Api authentication(Sanctum) with NuxtJs-Part1

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());
    }
Enter fullscreen mode Exit fullscreen mode

Testing Registration in Postman
image

We see we get all validation errors
image
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']);
image

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
        ];
    }
Enter fullscreen mode Exit fullscreen mode

For getting authenticated user

public function user()
    {
        return auth()->user();
    }
Enter fullscreen mode Exit fullscreen mode

Login testing in PostMan
image

We see when we enter nothing it gives us validation errors
image
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
image

public function logout()
    {

        auth()->user()->currentAccessToken()->delete();
        return [
            'message'=>'Successfully Logged out'
        ];
    }
Enter fullscreen mode Exit fullscreen mode

Testing Logout in PostMan
image
It shows unauthenticated without token
image
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
image
Postman Testing
image
If you try to access this route without token it will say give you a message of unauthenticated.
image

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

Discussion (0)