What is Laravel Sanctum?

Laravel Sanctum provides a  simple way for authenticating Single Page Applications(SPAs), Mobile Applications, and simple token-based APIs. It allows users to create multiple API tokens which they can use to access your application. The token themselves can have scopes that can be used to limit what can and cannot be accessed using the generated token.

Laravel provides multiple ways of authentication such as Social logins using Laravel SocialiteAPI authentication through oAuth using Laravel Passport, the basic session-based authentication using email and password and also API authentication using Laravel Sanctum.

In this article, I am going to show you how you can implement API authentication in your third party systems such as mobile applications using Laravel Sanctum.


How does Laravel Sanctum Work?

Laravel Sanctum is a simple package that is used to issue API tokens to users without the complication of OAuth. These tokens have a long expiration time but can be revoked at any time manually.

These Tokens are then stored in a single database table and can be authenticated by having them attached to the Authorization header.

This allows us to issue tokens from our server directly to our client/mobile applications.


Installation and Setup

To install the package, we can use the following command:

composer require laravel/sanctum

The next step is to publish the Sanctum configurations and the migration files using the vendor:publish command.

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

We can then run the database migrations. These migrations create a table that stores the API tokens assigned to the users.

 
php artisan migrate

To issue tokens for users, we need to use the Laravel\Sanctum\HasApiTokens trait in our User model.


use Laravel\Sanctum\HasApiTokens;

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

Laravel Sanctum Authentication Flow

Once the configurations are done, we can now start authentication. The first step is to issue API tokens. These tokens are used to authenticate API requests to the application. The token must be included in the Authorization Header as a Bearer Token. The header should be presented as follows:

 


 HEADERS { 
   'Content-Type' : 'application/json',
   'Authorization' : 'Bearer <TOKEN> ' 
}

In this case, the <TOKEN> is the generated API token that is used to identify the user/client making the request.

Registration

We can issue a token immediately after a user has been registered to our system like so.

To issue a token, we can use the createToken method.


public function register(Request $request)
{
     $user = User::create(
         'name' => $request->name,
         'email' => $request->email,
         'password' => Hash::make($request->password)
     );
   
     # And make sure to use the plainTextToken property
     # Since this will return us the plain text token and then store the hashed value in the database
     $token = $user->createToken('auth_token')->plainTextToken;

     return response()->json([
        "user"  => $user,
        "token"  => $token
     ]);

  }
    

By attaching the API token to the response body, we can retrieve the API token in our Single Page Application/Mobile Application in the frontend and store it. We can then use the stored API token to make requests to the server by attaching it to the headers of all requests.


Login

When a user provides their email/username and password during login, we can issue a token immediately after the authentication process is successful.


public function login(Request $request)
{
    if (!Auth::attempt($request->only('email', 'password'))) 

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

    $user = User::where('email',  $request->email)->firstOrFail();

    # Delete the existing tokens from the database and create a new one
    auth()->user()->tokens()->delete();

    $token = $user->createToken('auth_token')->plainTextToken;

    return response()->json([
        'user' => $user,
        'token' => $token
    ]);

}

API Structure Demonstration

For Demonstration, I will be using REST Client for VS Code , It makes it easier to put everything in one file and helps us understand about the process easily. So, let's create a file called api.rest and here we will be defining the API Structure, and define the contents of the file.

This file shows an example to get the currently authenticated user's data and this will only work once the user has successfully logged in, since we need to attach the plain text token in the request header.


# Variables declaration
@baseUrl = http://127.0.0.1:8000/api
# User's Plain Text Token goes here
@bearerToken = 1|91P7XlxutCs0TFazQu6dU8OjIiVlsRxUTddjVrxL

GET {{baseUrl}}/user
Content-Type: application/json
Accept: application/json
Authorization: Bearer {{bearerToken}}

Protecting routes

The only way to protect routes so that all the incoming requests are authenticated is by attaching the sanctum authentication guard to our API routes within the routes/api.php file. This can be done by adding an auth:sanctum middleware to the routes that require protection. In our example, the logout route requires the middleware because we want it to be only accessible if a user is signed in.


Route::group(['middleware' => ['auth:sanctum']],  function() {
    Route::post('logout', [UserAuthenticationController::class, 'logout']);
}

In this example, I have created a route group that will contain all the routes that need the auth:sanctum middleware


Laravel Sanctum vs Laravel Passport

Both Laravel Sanctum and Laravel Passport provide ways of API authentication. The main difference between the two is that Laravel Sanctum does not use OAuth Protocol while Laravel Passport uses the OAuth protocol to authenticate and authorize requests. Also, Sanctum is easier to use and is lightweight. If you are creating a small application that is a Single Page Application or a Mobile Application, you can use Laravel Sanctum for authentication. If the application you are building is massive, serves multiple clients and other third-party sites are to use the application for authentication purposes, you can use Passport.


Conclusion

Laravel Sanctum provides an easy and simple way of implementing API authentication for your frontend application. It is lightweight and thus easy to use and ship to production. This is because it does not use encryption keys to authenticate and thus has less infrastructure when shipping to production.  I hope this article was able to show you how to implement simple authentication using Laravel Sanctum. If you have any questions, feel free to ask them in the comment section below.