0
votes

I am using Laravel Sanctum in my project. I have created the middleware to add the authorization header (Bearer token) for every API request. Auth user has token but it is hashed in the database. I want to send the token (which is authorized) for the next requests. How can I get the authenticated token value (like JWT token)?

2
For that, you need to send Bearer token as authorization header with Axios in every request. For in-depth detail, you must watch below video tutorials. * Part 1: SPA Authentication using Laravel Sanctum * Part 2: API Token Authentication using SanctumTim

2 Answers

1
votes

You can get the plainTextToken only when it's first created. Once it's created, there is no way to get it again. It is returned in the token/create response body. Capture it and don't lose it, it will be the only way for that user to communicate/authenticate with your sanctum protected routes. Once it's created a hashed (non-decryptable) version is saved to the database. The plain text token that you save from the tokens/create method is hashed and compared to this to confirm the identity of the user. Unlike JWT, you won't get new iterations of the same token after creation.

See more here: https://laravel.com/docs/8.x/sanctum#issuing-api-tokens

0
votes

you cab catch token from header like this

        $token = null;
        $headers = apache_request_headers();
        if (isset($headers['Authorization'])) {
            if (strpos($headers['Authorization'], 'Bearer') !== false) {
                $token = str_replace('Bearer ', '', $headers['Authorization']);
            }
        }