Backend Discussion Laravel Security

Laravel Sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.

How It Works

Laravel Sanctum exists to solve two separate problems.

API Tokens

First, it is a simple package to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub “access tokens”. For example, imagine the “account settings” of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user at anytime.

Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming requests via the Authorization header which should contain a valid API token.

SPA Authentication

Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as a SPA created using Vue CLI.

For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel’s built-in cookie based session authentication services. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS. Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend.

Installation

You may install Laravel Sanctum via Composer:

composer require laravel/sanctum

Next, you should publish the Sanctum configuration and migration files using the vendor:publish Artisan command. The sanctum configuration file will be placed in your config directory:

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

Finally, you should run your database migrations. Sanctum will create one database table in which to store API tokens:

php artisan migrate

Next, if you plan to utilize Sanctum to authenticate an SPA, you should add Sanctum’s middleware to your api middleware group within your app/Http/Kernel.php file:

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Migration Customization

If you are not going to use Sanctum’s default migrations, you should call the Sanctum::ignoreMigrations method in the register method of your AppServiceProvider. You may export the default migrations using php artisan vendor:publish --tag=sanctum-migrations.

API Token Authentication

You should not use API tokens to authenticate your own first-party SPA. Instead, use Sanctum’s built-in SPA authentication.

Issuing API Tokens

Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.

To begin issuing tokens for users, your User model should use the HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

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

To issue a token, you may use the createToken method. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. API tokens are hashed using SHA-256 hashing before being stored in your database, but you may access the plain-text value of the token using the plainTextToken property of the NewAccessToken instance. You should display this value to the user immediately after the token has been created:

$token = $user->createToken('token-name');

return $token->plainTextToken;

You may access all of the user’s tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:

foreach ($user->tokens as $token) {
    //
}


Stan

Stan is an experienced full-stack developer and software engineer who is focused on web and game development. He is enthusiastic about new technologies. Stan is highly skilled in many programming languages and frameworks, and he always tries to deliver the best approach.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *