Home > Backend Development > PHP Tutorial > PHP security verification with Laravel Sanctum

PHP security verification with Laravel Sanctum

王林
Release: 2023-07-26 18:00:01
Original
981 people have browsed it

PHP security verification through Laravel Sanctum

Overview:
In modern web development, security verification is a crucial aspect. Laravel Sanctum is a simple and flexible authentication guard provided by Laravel, which can be used for front-end and back-end separation applications. This article will introduce how to use Laravel Sanctum to implement PHP security verification and provide relevant code examples.

Step 1: Install Laravel Sanctum

First, install the Sanctum extension package in the Laravel project. You can use Composer to install and run the following command:

composer require laravel/sanctum
Copy after login

Step 2: Configure Sanctum

After the installation is complete, Sanctum needs to be configured. Open the config/app.php file in the project root directory, find the providers array, and add the following code:

'providers' => [

    // ...

    LaravelSanctumSanctumServiceProvider::class,

],
Copy after login

Then, run the following command to publish Sanctum's Configuration file and database migration file:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"
Copy after login

Next, run the following command to perform database migration:

php artisan migrate
Copy after login

Step 3: Configure the authentication driver

During the setup process, You need to choose to use Sanctum as the default authentication driver. Open the config/auth.php file, find the guards array, and set the default guard to sanctum:

'defaults' => [
    'guard' => 'sanctum',
    // ...
],
Copy after login

Step 4: Enable Sanctum Middleware

Sanctum requires its own middleware to handle authentication. In order to enable Sanctum, the Authenticate middleware needs to be replaced with the middleware provided by Sanctum. Open the app/Http/Kernel.php file and add the following code to the $routeMiddleware array:

protected $routeMiddleware = [
    // ...
    'auth' => LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
];
Copy after login

Step 5: Generate Sanctum API Token

Sanctum provides API Token for authentication. API Token can be generated by the following code:

use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
}
Copy after login

This code uses the HasApiTokens trait in the User Model to generate API Token for the user.

Step 6: Protect the route

After using Sanctum for security verification, you can use the following code to protect the route that requires authentication:

Route::middleware('auth:sanctum')->group(function () {
    // 这里是需要保护的路由
});
Copy after login

The above code will apply Sanctum intermediate software to verify the user's API Token.

Step 7: Authentication

When the user submits a request through the front-end application, the following code can be used to authenticate:

use IlluminateHttpRequest;

Route::post('/login', function (Request $request) {
    $credentials = $request->only('email', 'password');
    
    if (Auth::attempt($credentials)) {
        $user = Auth::user();
        $token = $user->createToken('api')->plainTextToken;

        return response()->json([
            'user' => $user,
            'token' => $token,
        ]);
    } else {
        return response()->json(['error' => 'Unauthorized'], 401);
    }
});
Copy after login

The above code will be provided by the user Email and password to authenticate, and return a JSON response with user information and API Token.

Summary:
With Laravel Sanctum, we can easily implement security verification of PHP applications. This article explains how to install and configure Laravel Sanctum, and provides related code examples. I hope this article can be helpful to beginners and inspire more people to learn and use Laravel Sanctum.

Reference link:

  • [Laravel Sanctum GitHub official document](https://github.com/laravel/sanctum)

The above is the detailed content of PHP security verification with Laravel Sanctum. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template