Mobile Application Authentication using Token in Laravel

Are you using Laravel for the back-end of your mobile application? If yes, then probably you are looking for an easy solution for your mobile application authentication. Many users can be using your mobile app and you want to do authentication in order to serve content to your mobile users. In this article, we study how to do token-based authentication in Laravel. You can also use the same approach for REST API authentication.

We are going to integrate Laravel Sanctum which is a lightweight authentication system. You can consider it as a replacement for OAuth based authentication.

While using Sanctum, the user’s API tokens are stored in the database. This token must be sent as Bearer token via Authorization header from your mobile application to the Laravel API endpoints. These tokens typically have a very long expiration time (years).

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, you first need to install a Sanctum package to your Laravel application. Install it using the command:

composer require laravel/sanctum

After this, publish the configuration and migration files of Sanctum by running the below command.

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

By default, each request in Laravel requires a csrf token. In case of missing this csrf token, Laravel does not proceed with your request. When it comes to generating API tokens using Sanctum, we need to skip sending the csrf token. For this, add sanctum/token route to the $except variable of app/Http/Middleware/VerifyCsrfToken.php. I will create this sanctum/token route in the next steps.

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

For authentication purposes, we need to issue a token to the users. So, you have to use HasApiTokens trait to the User model as follows.

<?php

namespace App\Models;
...
use Laravel\Sanctum\HasApiTokens;

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

Issuing API Tokens for Authentication

In order to send a Bearer token with the Authorization header in each request, it requires first to issue an API token. I am going to create a method that generates an API token for each user. To issue a token, you will be required to send the email, password, and device of a user.

Add the below route in the routes/web.php

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

Next, create a controller APITokenController by the command:

php artisan make:controller APITokenController

Define the create_token() method in the newly created controller as follows.

<?php

namespace App\Http\Controllers;

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

class APITokenController 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 [
                'error' => 'The provided credentials are incorrect.'
            ];
        }
    
        return $user->createToken($request->input('device_name'))->plainTextToken;
    }
}

The above code first checks for the user’s credentials. If the credentials are correct then in response it sends a token in a plain text format. Here, I am receiving input values considering they will be sent in a JSON object.

Try to send a POST request with the user’s credentials and you should receive the plain text token. This API token may be stored on the mobile device and used in a header while sending API requests.

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

create-token

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

Sanctum will create multiple tokens whenever you hit the sanctum/token route with correct credentials. If you want to revoke the previous token then add the below statement before the last return statement of the above code.

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

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

Finally, protect the routes by adding the auth:sanctum middleware as follows.

Route::middleware('auth:sanctum')->get('/products', function () {
    // write a code
});

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 the API token as 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. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

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. Required fields are marked *