insidert

Guide on authenticating Mobile Application with Laravel Sanctum

A step-by-step guide

Note: This is an old guide may still work, please refer official laravel docs for the latest version.

  1. Install Sanctum composer require laravel/sanctum
  2. Publish the config file and migration php artisan vendor:publish — provider=”Laravel\Sanctum\SanctumServiceProvider”
  3. We do not need to make any changes to the config file but we need to run the migrations. php artisan migrate
  4. First, you need to expose an endpoint to register the users and save the details in the users table (Or any other table you prefer.) Usually, the endpoint would be /api/register if you are writing the routes in the api.php file.

If you are building the API, you may not use the default authentication scaffolding by laravel. That’s fine. Just validate the input, save the details.

Now, depending on the use-case, you may immediately need the token after creating the user or only need it after verifying the user by email or SMS. Of course, we need it at login too.

In any of the cases, before making the tokens, we need to setup Sanctum middleware.

// In your app\Http\Kernel.php file
// Import the middleware
// And add it to the API group.
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
'api' => [
    EnsureFrontendRequestsAreStateful::class,
    'throttle:60,1',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Let’s setup the Users Model too.

// In your User.php, import the trait
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    //
}

Now we are all set to creating the tokens and verifying the token for authenticated requests.

// In your registration controller,
// After creating the user,
$user = User::create(['user' => 'data']);
$token = $user->createToken($request->device_name)->plainTextToken;

// Save this token on the mobile device.
// May by with AsyncStorage or Realm if you are using React Native.
// logger($token) to use it to make the requests while testing.
return $token;

The documentation has a good example on how to do this at login.

Don’t forget to save the token on your mobile app.

Now, if you check the database, you can see a new record in personal_access_tokens table.

  1. tokenable_type: User model (Because we are using on users table.)
  2. tokenable_id: (Id of the user on the database.)
  3. name: (Usually device name or any other name can be given based on your needs.)
  4. token: Hashed token
  5. Abilities: What a user can do with this token
  6. last_used_at: Updated whenever users request with their token

Protecting routes

// Protect all your routes with auth:sanctum middlware.
Route::middleware('auth:sanctum')->group(function () {
    Route::post('user', function (Request $request) {
    return 'Hello there';})
    
   // Other routes here
});

Making requests with the token from the Mobile App.

With the token on the Mobile App, you need to access the protected routes/endpoints with Authorization header.

If you are using Postman to check the API, go to Authorizations tab and select Bearer Token and paste the token generated by the function for a particular user.

This is where things may not work. To get the token, you will open the local database - usually phpmyadmin, copy the token, paste it and makes a request. You will get this response. {“message”: “unauthenticated”}

Fixing the unauthenticated message issue in Laravel Sanctum.

I have stumbled upon this so I emphasized this section. We need to make the request with the token generated by the function but not with the token saved on the database.

So, while testing, use logger function to save it in the logs or just log the response in your mobile application.


#laravel
#laravel Sanctum
#code