Mobile Application Authentication using Token in Laravel

Are you using Laravel as a back-end for the mobile application? If yes, then probably you are looking for an easy solution for mobile application authentication. For your mobile app users, you want to have authentication in order to serve content to them. In this article, we study how to perform mobile application authentication with Laravel.

We’ll use Laravel Sanctum which is a lightweight authentication system. It can be considered as a replacement for OAuth-based authentication. Instead of OAuth, it follows token-based authentication.

While using Laravel Sanctum, each user will get a unique token. These tokens are stored in the database. Laravel typically sets very long expiration times (years) for these tokens. This token needs to be sent as a Bearer token via Authorization header from your mobile application to the Laravel API endpoints. On the server side, these tokens will be validated and requests will execute.

That being said, let’s take a look at how to use Sanctum for authenticating mobile applications.

Install and Configure Laravel Sanctum

For getting started, make sure you have a Sanctum package in your Laravel application. The recent versions of Laravel ships with Sanctum. However, if you don’t have laravel/sanctum in your composer.json, install it using the command:

composer require laravel/sanctum

After this, publish the configuration and migration files of Sanctum.

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

Next, run the migration command which will create a personal_access_tokens table in your database. This is the table where all API tokens will be stored.

php artisan migrate

As you need to issue a token to the users, you have to use the HasApiTokens trait in the User model.

<?php
 
namespace App\Models;
...
use Laravel\Sanctum\HasApiTokens;
 
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    ...
}

Issuing API Tokens for Authentication

To receive a token for the mobile app user, it needs to send a request to the Laravel route from the mobile app. The request will accept email, password, and device name. Let’s define the route for it.

Route::post('/sanctum/token', 'APIController@create_token');

Next, create the APIController using the Artisan command:

php artisan make:controller APIController

Define the create_token() method in this controller as follows.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class APIController extends Controller
{
    public function create_token(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
            'device_name' => 'required',
        ]);
     
        $user = User::where('email', $request->input('email'))->first();
 
        if (! $user || ! Hash::check($request->input('password'), $user->password)) {
            return response()->json([
                'error' => 'The provided credentials are incorrect.'
            ]);
        }

        $token = $user->createToken($request->input('device_name'))->plainTextToken;

        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer'
        ]);
    }
}

The above code first checks for the user’s credentials. If the credentials are correct then only it sends a token in response.

Usually, Laravel requires a csrf token in each request. If the csrf token is missing, Laravel does not proceed with your request. To call the sanctum/token route, we need to skip sending the csrf token. For this, add sanctum/token route to the $except variable of app/Http/Middleware/VerifyCsrfToken.php file.

<?php
...
class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
        'sanctum/token'
    ];
}

Now send a POST request to the sanctum/token route. Pass email, password, and device name in the request. You will get the API token that may be stored on the mobile device. This token should be sent in an Authorization header while calling subsequent API endpoints.

In my case, I use the Rest Client extension of VS code, and my request to sanctum/token is as shown in the screenshot below.

sanctum-create-token

Head over to the database and you should see the token is stored in the personal_access_tokens table.

Revoke Token

Sanctum will create a new token whenever you hit the sanctum/token route. To revoke the previous token, call the delete() method on the user’s token as follows.

// Revoke previous tokens
$user->tokens()->delete();

$token = $user->createToken($request->input('device_name'))->plainTextToken;

Mobile Application Authentication

The final step is to protect the routes behind the authentication using Sanctum. You can do it by adding the auth:sanctum middleware as follows.

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/products', function () {
        // Uses auth:sanctum middleware
    });

    Route::get('/customers', function () {
        // Uses auth:sanctum middleware
    });
});

The middleware validates if the token is received in an Authorization header. If the API token is correct then only it allows proceeding for the route.

As an example, in VS code you can send a Bearer token with the Authorization header as shown below.

send-token

I hope you understand how to integrate mobile application authentication using a token in Laravel. You can now build a more robust mobile application with the help of Laravel.

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published.