📜  laravel sanctum auth setup - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:32:33.760000             🧑  作者: Mango

Laravel Sanctum Auth Setup

Laravel Sanctum is a lightweight package for SPA authentication in Laravel applications. This tutorial will guide you through the setup process for Laravel Sanctum authentication in your Laravel project.

Prerequisites

Before we start with the Laravel Sanctum installation and setup, make sure you have the following installed on your system:

Installation

Install Sanctum via Composer by running the following command in your terminal:

composer require laravel/sanctum
Configuration

Once installation is complete, run the following command to publish the Sanctum configuration file:

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

This will create a sanctum.php configuration file in your application's config directory.

Next, you'll need a database table to store tokens, so run the following command to create the Sanctum migration file:

php artisan sanctum:install

Finally, run your database migrations:

php artisan migrate
Usage

With your configuration set up, you can now use Laravel Sanctum for authentication in your application.

First, add the HasApiTokens trait to your authenticatable model (e.g. User model):

use Laravel\Sanctum\HasApiTokens;

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

Next, in your controller or route, generate a token for the authenticated user and return it as part of the response:

use Illuminate\Http\Request;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    $user = $request->user();
    $token = $user->createToken('token-name')->plainTextToken;

    return [
        'user' => $user,
        'token' => $token,
    ];
});

This will generate a unique token for the authenticated user, which can be used for subsequent API requests to authenticate the user.

And that's it, you're all set up with Laravel Sanctum authentication in your Laravel application.

Conclusion

In this tutorial, we've covered the installation and configuration steps for Laravel Sanctum authentication in Laravel 8. With the HasApiTokens trait and a few lines of code, you can quickly set up secure authentication for your single-page applications.