Axios header doesn’t work Laravel and Vue.js

  axios, bearer-token, javascript, laravel, php

I’m using Laravel’s Sanctum library to authenticate my API, but it just doesn’t work and everything seems on purpose.

I’m creating a token after someone authenticates, and it goes into personal_access_token table in database. And then I insert the token into metatag. Then I retrieve the content of the metatag with default javascript (it works) and set it as global authorization header to Axios in bootstrap.js file.

When using the decrypted bearer token, this approach was working. But when I started to use the default token column on personal_access_token, it doesn’t work.

The way I define my token

protected function authenticated(Request $request, $user)
        $user->access_token = $user->createToken('api-token')->plainTextToken;

        return $request->wantsJson() ? response()->json($user, 200) : redirect()->intended('/students');

That works good. It inserts new token after someone authenticates.

The way I set token as content of metatag

<meta name="access-token" content="{{auth()->user()->tokens()->first()->token}}" />

I can see the token when I inspect, it is like this: fd34a554cc5a6f14004f8728735375f980d81053b97f719be5bd504647d786cf

The way I set the token as global header to Axios

let metatag = document.querySelector('meta[name="access-token"]').content;

window.axios = require('axios');

axios.defaults.headers.common['Authorization'] = `Bearer ${metatag}`;

There were no problem with that, until I switched to personal_access_table. That approach was working when I used a token like 6|yqbI....

Source: Laravel

Leave a Reply