skip to Main Content

I have a small project using Laravel and Vue.js. I implemented a simple authentication system using Sanctum, based on YouTube tutorials and the official documentation. It works correctly; however, I am concerned about storing the JWT on the client-side using local storage, as I believe it is not a secure way to handle authentication tokens. While searching on Google, I came across the "http-only" approach. How can I implement this in Laravel 9.52? I noticed that many tutorials are for older versions of Laravel and do not work for me 🙁

2

Answers


  1. Chosen as BEST ANSWER

  2. Sanctum has two ways to authenticate users, through Laravel’s built-in cookie based session or API Token in an Authorization header.

    If you uses the cookie then you have nothing more to do.

    If you uses the token you need to store it somewhere on the client side, you have (basically) two options : localstorage or cookie.
    But Sanctum is only looking for it inside the Authorization header, so you need to retrieve it (storage/cookie) before inserting it in the request header. So your cookie can’t be http-only…

    An other solution could be to send it in a http-only cookie and get sanctum to retrieve it by creating your own callback for LaravelSanctumGuard::getTokenFromRequest() by adding this in the boot method of your AppServiceProvider :

    Sanctum::getAccessTokenFromRequestUsing(function($request) {
        return $request->cookie('your_cookie_token_name');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search