API authentication using Laravel Sanctum in Laravel 8

API authentication using Laravel Sanctum in Laravel 8

In this tutorial, We'll look at how to utilize Laravel Sanctum to easily authenticate API calls and secure your Laravel 8 app. Laravel Sanctum makes it easy to develop safe and scalable APIs for your Laravel apps by providing a simple and straightforward mechanism to verify API calls. We'll walk you through installing Laravel Sanctum and utilizing it to authenticate API queries. So let's get this party started!

What is Laravel Sanctum

Laravel Sanctum is a Laravel package that provides a lightweight authentication system for single-page applications (SPAs), mobile applications, and simple, token-based APIs. It allows users to login to the application using a traditional email and password combination and provides access to protected routes and endpoints using personal access tokens. Laravel Sanctum also includes support for multiple authentication guards, including traditional web sessions and API tokens.

To implement API authentication using Laravel Sanctum in Laravel 8, follow these steps:
  1. Install Laravel Sanctum using Composer by running the following command:
Copy codecomposer require laravel/sanctum
  1. Add the Sanctum service provider to your config/app.php configuration file by adding the following line to the providers array:
Copy codeLaravel\Sanctum\SanctumServiceProvider::class,
  1. Publish the Sanctum configuration file by running the following Artisan command:
Copy codephp artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  1. In the config/sanctum.php configuration file, set the stateful option to true to enable stateful authentication. This means that the authenticated user will remain authenticated until they explicitly log out.

  2. In your routes/api.php file, add the auth:sanctum middleware to the routes that require authentication:

Copy codeRoute::middleware('auth:sanctum')->group(function () {
    // Your protected routes here
});
  1. Run the migrations to create the required database tables by running the following command:
Copy codephp artisan migrate
  1. In your config/auth.php configuration file, set the guards and providers options to use Sanctum for API authentication:
Copy code'guards' => [
    'api' => [
        'driver' => 'sanctum',
        'provider' => 'users',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
],
  1. In your user model, add the HasApiTokens trait to enable Sanctum token authentication for your users:
Copy codeuse Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;

    // Your user model code here
}
  1. To generate an authentication token for a user, use the createToken method on the user instance:
Copy code$user = User::find(1);

$token = $user->createToken('My Token Name')->plainTextToken;
  1. To authenticate a request with an API token, include the token in the Authorization header with the Bearer prefix:
Copy codeAuthorization: Bearer <token>
  1. To log out a user and revoke their tokens, use the logout method on the user instance:
Copy code$user = User::find(1);

$user->logout();

With these steps, you can successfully implement API authentication using Laravel Sanctum in Laravel 8.

Conclusion

Laravel 8 API Authentication using Laravel Sanctum provides a simple and secure way to authenticate API requests. With its easy-to-use and customizable features, developers can easily implement this authentication method in their Laravel projects to ensure the safety and security of their data and applications.