Home  >  Article  >  PHP Framework  >  Laravel development: How to provide API authentication for SPA using Laravel Sanctum?

Laravel development: How to provide API authentication for SPA using Laravel Sanctum?

WBOY
WBOYOriginal
2023-06-13 09:19:041693browse

Laravel Development: How to provide API authentication for SPA using Laravel Sanctum?

With the popularity of Single Page Applications (SPA), we need a reliable way to protect our APIs from unauthorized access and attacks. Laravel Sanctum is a lightweight authentication system provided by Laravel that provides easy authentication for SPA. This article will show you how to use Laravel Sanctum to provide API authentication for your SPA.

Using Laravel Sanctum

Laravel Sanctum is an official package in Laravel 7.x version for API authentication. Laravel Sanctum uses the API's token to identify the user, and can easily perform multiple authentication builds by using the token.

Install Laravel Sanctum

First, make sure the Laravel framework is installed.

To install laravel sanctum, you can use the following command

composer require laravel/sanctum

Add the ServiceProvider to the providers list in the config/app.php file.

'providers' => [
    // ...
    LaravelSanctumSanctumServiceProvider::class,

],

Now, you can run the following commands to publish the necessary database migrations and Sanctum configuration.

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

Execute the following command to run the migration:

php artisan migrate

Use Sanctum for default authentication

Sanctum contains default implementations for API and Single Page Application authentication. Default authentication can be enabled by using the SanctumTraitsHasApiTokens trait for the user model.

Add the HasApiTokens trait to the user model

<?php

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use LaravelSanctumHasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    // ...
}

For better explanation, we will use a simple SPA example. Assume the URL for the example is http://spa.test and the API is exposed via http://api.spa.test.

Configuring CORS in Laravel

Add the following code to the app/Providers/AppServiceProvider.php file to allow cross-domain resource sharing (CORS).

...
use IlluminateSupportFacadesSchema;
use IlluminateSupportFacadesURL;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Schema::defaultStringLength(191);

        if (config('app.env') === 'production') {
            URL::forceScheme('https');
        }

        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Request-With',
            'Access-Control-Allow-Credentials' => 'true',
        ];
        $this->app['router']->middleware('api')->get('/sanctum/csrf-cookie', function () {
            return response()->json(['status' => 'success']);
        });

        foreach ($headers as $key => $value) {
            config(['cors.supportsCredentials' => true]);
            config(['cors.paths.api/*' => [
                'allowedOrigins' => ['http://spa.test'],
                'allowedHeaders' => [$key],
                'allowedMethods' => ['*'],
                'exposedHeaders' => [],
                'maxAge' => 86400,
            ]]);
        }
    }
}

Replace http://spa.test in the above code with the URL of your SPA.

Token Validation and API Protection Instructions

In the controller we can use Sanctum's auth middleware to secure the route

public function index(Request $request)
{
    $user = $request->user();
    // ...
}

public function store(Request $request)
{
    $user = $request->user();
    // ...
}

public function destroy(Request $request, string $id)
{
    $user = $request->user();  
    // ...
}

public function update(Request $request, string $id)
{
    $user = $request->user();
    // ...
}

This will be obtained from the request header Sanctum authorizes the token and uses that token to authenticate the user. If the authorization token is not provided in the header, a 401 Unauthorized error will be returned.

Issuing Authorization Token Request

In our SPA, we can use the axios library to use the API and get the token. To get the authorization token, we need to get the CSRF token first, so we need to send a GET request to get it.

axios.get('http://api.spa.test/sanctum/csrf-cookie').then(response => {
    axios.post('http://api.spa.test/login', {
        username: this.username,
        password: this.password
    }).then(response => {
        axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
        this.$router.push({ name: 'home' });
    });
});

The above code will make a POST request in http://api.spa.test, create a new Sanctum authorization token on the server, and respond with the token as response.data.token . Thereafter, we can add the token to axios' common header to use it in the SPA for all subsequent requests.

Note that this example assumes there is a route named "login".

Sanctum also provides us with a logout route to revoke authorization tokens.

axios.post('http://api.spa.test/logout').then(response => {
    delete axios.defaults.headers.common['Authorization'];
    this.$router.push({ name: 'login' });
});

Conclusion

Laravel Sanctum is a lightweight, simple and practical authentication system. It is easy to integrate and use, and provides default authentication functions. It is excellent for SPA authentication. solution. Once you use Sanctum, you will no longer need to write your own authentication system. It allows us to quickly implement secure authentication for our API and allows our SPA to interact with the API in a fraction of the time.

The above is the detailed content of Laravel development: How to provide API authentication for SPA using Laravel Sanctum?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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