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 fir…


This content originally appeared on DEV Community and was authored by Tanzim Ibthesam

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
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
        ];
    }

For getting authenticated user

public function user()
    {
        return auth()->user();
    }

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'
        ];
    }

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 blog we will mention about how to intergrate it on frontend with Nuxt.js


This content originally appeared on DEV Community and was authored by Tanzim Ibthesam


Print Share Comment Cite Upload Translate Updates
APA

Tanzim Ibthesam | Sciencx (2021-10-11T07:52:53+00:00) Laravel Api authentication(Sanctum) with NuxtJs-Part1. Retrieved from https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/

MLA
" » Laravel Api authentication(Sanctum) with NuxtJs-Part1." Tanzim Ibthesam | Sciencx - Monday October 11, 2021, https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/
HARVARD
Tanzim Ibthesam | Sciencx Monday October 11, 2021 » Laravel Api authentication(Sanctum) with NuxtJs-Part1., viewed ,<https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/>
VANCOUVER
Tanzim Ibthesam | Sciencx - » Laravel Api authentication(Sanctum) with NuxtJs-Part1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/
CHICAGO
" » Laravel Api authentication(Sanctum) with NuxtJs-Part1." Tanzim Ibthesam | Sciencx - Accessed . https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/
IEEE
" » Laravel Api authentication(Sanctum) with NuxtJs-Part1." Tanzim Ibthesam | Sciencx [Online]. Available: https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/. [Accessed: ]
rf:citation
» Laravel Api authentication(Sanctum) with NuxtJs-Part1 | Tanzim Ibthesam | Sciencx | https://www.scien.cx/2021/10/11/laravel-api-authenticationsanctum-with-nuxtjs-part1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.