Laravel 10 - API Authentication using Laravel Sanctum

By Ved Prakash N | Dec 24, 2023 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-10-api-authentication-using-laravel-sanctum

Laravel Sanctum api authentication Tutorial step by step


In this post, you will learn how to make an API authentication using Laravel Sanctum in Laravel 10. So guys lets get started

Step 1: Install Laravel Application using the below command:

composer create-project laravel/laravel example-app


Step 2: Connect Database using .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=


Step 3: Install Sanctum using the below command via composer:

composer require laravel/sanctum

After successfully installing the package, we need to publish the configuration file with the following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

finally, run the migrations. Sanctum will create one database table in which to store API tokens:

php artisan migrate


Step 4: Add Sanctum's middleware to your API middleware group within your application's app/Http/Kernel.php file:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],


Step 5: Issuing API Tokens in Eloquent Model app/Models/User.php. User model should use the Laravel\Sanctum\HasApiTokens trait.

In model, we added HasApiTokens trait of Sanctum. Which will be already present in Laravel 10.x versions.

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

...
}


Step 6: Create a controller using the following command:

php artisan make:controller Api/UserAuthController

After successfully creating the controller, let's open the controller from the following path: app\Http\Controllers\Api\UserAuthController.php and paste the below code:

<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserAuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        $registerUserData = $request->validate([
            'name'=>'required|string',
            'email'=>'required|string|email|unique:users',
            'password'=>'required|min:8'
        ]);

        try {

            $user = User::create([
                'name' => $registerUserData['name'],
                'email' => $registerUserData['email'],
                'password' => Hash::make($registerUserData['password']),
            ]);

            $tokenName = 'fundaToken'.rand(111,999);
            $token = $user->createToken($tokenName)->plainTextToken;

            return response()->json([
            'status' => 201,
                'message' => 'User Created Successfully',
                'data' => [
                    'user' => $user,
                    'access_token' => $token,
                    'token_type' => 'Bearer',
                ]
            ], 201);

        } catch (\Throwable $th) {

            return response()->json([
                'message' => 'Something went wrong'.$th->getMessage(),
                'status' => 500
            ], 500);
        }
    }

    public function login(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required','min:8'],
        ]);

        try {

            $user = User::where('email',$credentials['email'])->first();

            if(!$user || !Hash::check($credentials['password'],$user->password)){

                return response()->json(['message' => 'Invalid Credentials'], 401);
            }

            if (Auth::attempt($credentials)) {

                $tokenName = 'fundaToken'.rand(111,999);
                $token = $user->createToken($tokenName)->plainTextToken;

                return response()->json([
            'status' => 200,
                        'message' => 'Login Successful',
                        'access_token' => $token,
                        'token_type' => 'Bearer',
                    ], 200);
            }else{

                return response()->json(['message' => 'Invalid credentials'], 401);
            }

        } catch (\Throwable $th) {

            return response()->json([
                'message' => 'Something went wrong'.$th->getMessage(),
                'status' => 500
            ], 500);
        }
    }

    public function logout()
    {
        $user = User::findOrFail(Auth::id());
        $user->tokens()->delete();

        return response()->json([
            'status' => 200,
            'message' => 'Logged out successfully'
        ], 200);
    }

    public function user()
    {
        if(Auth::check()){

            $user = Auth::user();

            return response()->json([
                'message' => 'User Detail',
                'data' => $user,
            ], 200);
        }
        else
        {
            return response()->json([
                'message' => 'Login to continue'
            ], 200);
        }
    }
}


Step 7: Create API Routes. Go to routes/api.php file and build an API for this controller

Route::controller(App\Http\Controllers\Api\UserAuthController::class)->group(function(){
    Route::post('login', 'login');
    Route::post('register', 'register');
});

Route::middleware(['auth:sanctum'])->controller(App\Http\Controllers\Api\UserAuthController::class)->group(function(){
    Route::get('logout', 'logout');
    Route::get('user', 'user');
});


Finally, we have created the Sanctum API Token Authentication in Laravel 10.

Now let's begin to check the APIs using Postman.

Note: We can try our API but in the request header don’t forget to add

Accept => application/json


1. Register User by API using Postman as shown below: 

API: http://localhost:8000/api/register , Method: POST 

Add the Header - Key: Accept , Value: application/json


Once the user is created, you will get the Token and User details in the response.


2. Login User by API using Postman as shown below: 

API: http://localhost:8000/api/login , Method: POST 

Add the Header Key: Accept , Value: application/json


Once the user is Logged In Successfully, it will give the Token (access_token) and the Token_Type for Authorization


3. Let's get the User Detail using the API

This API ( http://localhost:8000/api/user ) which is protected by auth sanctum middleware. So to access this API you have to provide the Bearer "Token" (You received it while login as "access_token" )

API: http://localhost:8000/api/user , Method: GET

Add the Header Key: Accept , Value: application/json

3.1 - With Authorization and Bearer Token: ( Add the Access Token )



3.2 - Without Authorization and Bearer Token:



4. Logout User by API using Postman as shown below:

API: http://localhost:8000/api/logoutMethod: GET

Add the Header Key: Accept , Value: application/json

Add the Authorization - Bearer Token



That's It. We have completed Laravel Sanctum API Authentication successfully.

Thanks for reading.

https://www.fundaofwebit.com/post/laravel-10-api-authentication-using-laravel-sanctum

Share this blog on social platforms