Laravel Api authentication(Sanctum) with NuxtJs-Part1
Tags: laravel, php, vue, programming
Published: 2021-10-11 07:52:53

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjjz5u9yt3ktel8rma9x.png)
 
We see we get all validation errors 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8s893u5xq52t79u7jh7.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkmfma8d4cem8rtvi9vl.png)
 
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bejpskh8ixw39ntxyy7c.png)
 
We see when we enter nothing it gives us validation errors
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gm951cmabrfbatksvs2f.png)
 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2vb4mjemd554wdpo8y8.png)
 
```
public function logout()
    {
        
        auth()->user()->currentAccessToken()->delete();
        return [
            'message'=>'Successfully Logged out'
        ];
    }
```
**Testing Logout in PostMan**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2vayijk7tt3b4x3rma1y.png)
It shows unauthenticated without token 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/au3ijjtzzsd1y3wgi3bm.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h81jc16khmkcjmeo7xvp.png)
**Postman Testing**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/492mgn3qc12ojy52asjz.png)
If you try to access this route without token it will say give you a message of unauthenticated.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iy3aincnybewldz35k8e.png)
  
 We are very much done with Laravel api authentication registration,login and logout.In the [next part](https://dev.to/tanzimibthesam/laravel-api-authentication-sanctum-with-nuxtjspart-2-4ce1) blog we will mention about how to intergrate it on frontend with Nuxt.js