Why Sanctum is the best fit for SPA authentication.

Why Sanctum is the best fit for SPA authentication.

Authentication and authorization are crucial aspects of software development, today we will see how Sanctum is the best suit for SPA(Single Page Application) and mobile API authentication and authorization. Laravel has two major packages that are Laravel Passport and Laravel Sanctum depending on the use case you can choose one of them, but when it's about SPA and you don't have any need for the OAuth2 going with Sanctum will be the best, we will discuss why and how?

Laravel Sanctum primarily solves two problems

  1. API TokensSanctum provides API tokens without the complication of OAuth by providing personal access tokens inspired by GitHub and other applications that use personal authentication tokens for authentication and authorization. Sanctum achieves this by storing the access token in the database and authorizing incoming HTTP requests via the Authorization header.
  2. SPA AuthenticationSanctum offers an easy way to authenticate Single Page Applications (SPA), communicating with the APIs developed using Laravel. You can use Sanctum whether you are using a separate application for frontend developed in Vue or React, or you are using Laravel with Vue or React with Laravel in one project.Sanctum uses the default cookie-based service for authentication that comes in the default authentication for the web in Laravel, That's why you don't need any token-based authentication for your Single Page Application.The benefits of using this is you will get CSRF Protection and session authentication, and also gives protection against the leakage of authentication credentials vis XSS(Cross-Site Scripting.).It is not compulsory to use cookie-based authentication, you can use token-based authentication also. Sanctum will only use cookie-based authentication if it's coming from your SPA otherwise it will look for the Authorization header for a valid API token.As of now, we have a detailed introduction to Sanctum and the working mechanism, so now we will explore how to implement it in our application.
  3. Sanctum ImplementationInstallation

 composer require laravel/sanctum        

  1. Publish Configuration

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

  1. Run migrationTo create a table in your database to store authentication tokens

 php artisan migrate        

  1. Adding MiddlewareIf you want to use the sanctum for your Single Page Application (SPA) you should add the below middleware to your api middleware group or else you can ignore this step. The EnsureFrontendRequestsAreStateful middleware to the API middleware group. This middleware is provided by Sanctum and is crucial for ensuring that authentication tokens are properly handled between the SPA and the backend. It maintains the statefulness of the authentication session, allowing users to remain logged in while navigating your SPA.

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

  1. Configure CORS (Cross-Origin Resource Sharing)CORS is a security feature implemented in web browsers to control which web pages can access resources on a given domain. In this step, you are configuring your Laravel application to allow requests from your SPA's domain. By specifying your SPA's URL in the allowed_origins array, you are permitting it to make requests to your Laravel application. This step ensures that your SPA can communicate with your API without encountering CORS-related issues.Add the below code in config/cors.php add your SPA URL in paths array.

 'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
 'allowed_methods' => ['*'],
 'allowed_origins' => [env('SPA_URL')], // your SPA URL
 'allowed_origins_patterns' => [],
 'allowed_headers' => ['*'],
 'exposed_headers' => [],
 'max_age' => 0,
 'supports_credentials' => true,        

  1. Create API RoutesCreate your API routes in the routes/api.php file.

 use App\Http\Controllers\API\AuthController;
 use App\Http\Controllers\API\YourController;

 Route::prefix('auth')->group(function () {
     Route::post('/login', [AuthController::class, 'login']);
     Route::post('/register', [AuthController::class, 'register']);
     Route::middleware('auth:sanctum')->post('/logout', [AuthController::class, 'logout']);
 });

 Route::middleware('auth:sanctum')->group(function () {
     Route::get('/user', [AuthController::class, 'user']);
 });        

  1. Implement SPA AuthenticationIn your SPA (Single Page Application), you need to implement the frontend logic for user authentication. Here, Axios, a popular HTTP client for JavaScript, is configured to handle requests. Axios is used to send HTTP requests to your Laravel API. The withCredentials property is set to true to include credentials (such as cookies) with requests. The login and logout functions demonstrate how to perform user login and logout operations. These functions handle sending requests to the appropriate API endpoints (/api/auth/login and /api/auth/logout) and manage the user's authentication status in your SPA.


 axios.defaults.withCredentials = true;

 async function login(email, password) {
     try {
         await axios.get('/sanctum/csrf-cookie');
         await axios.post('/api/auth/login', {
             email: email,
             password: password
         });

     } catch (error) {

     }
 }

 async function logout() {
     try {
         await axios.post('/api/auth/logout');

     } catch (error) {

     }
 }
        

Conclusion Laravel Sanctum emerges as the top choice for Single Page Applications (SPAs) seeking secure and streamlined authentication solutions. Unlike its counterpart Laravel Passport, Sanctum simplifies the complex process of API token management and offers effortless SPA authentication. By storing access tokens securely and employing cookie-based authentication, Sanctum ensures robust security measures, including CSRF protection and defense against cross-site scripting attacks. Its seamless integration capabilities make it a preferred option for developers, allowing them to focus on building user-friendly, secure SPAs without the complexities of intricate authentication systems. Sanctum’s simplicity, enhanced security, and seamless integration make it the go-to solution for modern SPAs in the ever-evolving landscape of web development.

要查看或添加评论,请登录

Abhishek Jha的更多文章

  • Laravel blade

    Laravel blade

    Laravel Blade, the built-in templating engine in Laravel, is the magician behind the scenes making web development a…

  • How to make code clean and consistent.

    How to make code clean and consistent.

    In this article, we will discuss the default CLI app that comes with Laravel 9 to make your code clean and consistent…

    2 条评论

社区洞察

其他会员也浏览了