DEV Community

Cover image for API Authentication using Laravel Sanctum
Chinonso Ikewelugo
Chinonso Ikewelugo

Posted on

API Authentication using Laravel Sanctum

In this tutorial, we’re going look at what the Laravel Sanctum package is and what it does.
Sanctum is a Laravel package which provides a simple means for authenticating your SPAs, mobile apps, and simple token-based APIs.
Let’s get right to it.

#Step 1
We will begin by creating a new Laravel project.

laravel new lara-vue
Enter fullscreen mode Exit fullscreen mode

I’m using Laragon for my local development, so I can access my project by visiting http://lara-vue.test. You can access yours according to the configurations of your local server
Next, create your database and edit the contents of the .env file in your app’s root directory.

DB_CONNECTION = mysql
DB_HOST = 127.0.0.1
DB_PORT = 3306
DB_DATABASE = YourDBName
DB_USERNAME = YourDBUsername
DB_PASSWORD = YourDBPassoword
Enter fullscreen mode Exit fullscreen mode

#Step 2
We can now install Laravel Sanctum

composer require laravel/sanctum
Enter fullscreen mode Exit fullscreen mode

After installation, we will publish the Sanctum configuration and migration files using the vendor:publish Artisan command.

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Enter fullscreen mode Exit fullscreen mode

This command will place the configuration file in the config directory of our project.
Next, we run the database migrations. Sanctum will create a database table in which to store API tokens.

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Output

Migration table created successfully.
...
Migrating: 2019_12_14_000001_create_personal_access_tokens_table
Migrated:  2019_12_14_000001_create_personal_access_tokens_table (1,081.77ms)
Enter fullscreen mode Exit fullscreen mode

You will notice that a personal_access_tokens table has been added to your database. This is where the user tokens will be stored.

Next, add Sanctum's middleware to your API middleware group in the app/Http/Kernel.php file

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
]
Enter fullscreen mode Exit fullscreen mode

#Step 3
To use tokens to authenticate users, we have to add the HasApiToken trait to the app/models/User model.

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    ...
}
Enter fullscreen mode Exit fullscreen mode

When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.

#Step 4
Let us now create our authentication routes in the routes/api.php file

use App\Http\Controllers\AuthController;

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login'])->name('login');

Route::middleware('auth:sanctum')->group(function () {
    Route::post('/logout', [AuthController::class, 'logout']);
});
Enter fullscreen mode Exit fullscreen mode

If you noticed, we called AuthController without creating it. Let us create it using this simple command

php artisan make:controller AuthController
Enter fullscreen mode Exit fullscreen mode

Now, in our AuthController,

    public function register(Request $request)
    {
        try{
            $attributes= $request->validate(
                [
                    'name'=>'required|min:3|max:30',
                    'email'=>'required|email|unique:users',
                    'password'=>'required|min:6|max:30',
                ]
            );

            $attributes['password']= bcrypt($attributes['password']);

            $user = User::create($attributes);

            $message= "Account created successfully, welcome aboard.";
            $success= true;
        } catch(Exception $e){
            $success= false;
            $message= $e->getMessage();
        }


        $response= [
            'success'=>$success,
            'message'=>$message,
        ];

        return response()->json($response);
    }

    public function login(Request $request)
    {
        $attributes= $request->validate(
            [
                'email'=>'required|email',
                'password'=>'required',
            ]
        );

        if(!auth()->attempt($attributes)){
            return response()->json(
                ['message'=>'These credentials do not match our records'], 401
            );
        }

        $user= auth()->user();
        $token= $user->createToken($user->id)->plainTextToken;

        $message= "User logged in successfully";
        $success= true;

        $response= [
            'success'=>$success,
            'message'=>$message,
            'data'=>[
                'user'=>$user,
                'token'=>$token,
            ],
        ];     

        return response()->json($response, 200);
    }


    public function logout()
    {
        Session::flush();
        $success= true;
        $message= 'User logged out successfully';

        $response= [
            'success'=>$success,
            'message'=>$message,
        ];

        return response()->json($response);
    }
Enter fullscreen mode Exit fullscreen mode

Here, we set up our authentication logic. The register method creates a new user in our app, the login method authenticates users and generates an access token on succesful login, and the logout method removes the user's session.

#Step 5
All we have left to do is test our implementation. We can do this using Postman or Insomnia packages. We'll send requests to our register and login routes.

If everything works well, we will receive a JSON response similar to this:
Registration Response:

{
    "success":true,
    "message":"Account created successfully, welcome aboard."
}
Enter fullscreen mode Exit fullscreen mode

Login Response:

{
    "success":true,
    "message":"User logged in successfully"
    "data":{
        "user": {
            "id": 1,
            "name": "Emeka Ike",
            "email": "emekaike@test.com",
            "email_verified_at": null,
            "created_at": null,
            "updated_at": null
        },
        "token": "uIuSGRGAblahGHblah..."
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion
In this tutorial, we looked at what Laravel Sanctum is and what it does. We covered how to install and setup Sanctum, and how to use it to authenticate and give access to users. This gives us the power to build powerful APIs.

You can view the source code for this tutorial here.

I hope you found this helpful, and if you have any questions, just let me know in the comments and I will clarify further.

Discussion (0)