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

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
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),