How to resolve Laravel 401 (Unauthorized) error for a particular single URL.
url is accessible directly but when request send using axios its how this error.
How to resolve Laravel 401 (Unauthorized) error for a particular single URL.
url is accessible directly but when request send using axios its how this error.
api_token: this.user.api_token
axios.post("http://foo",
{headers: { 'Authorization' : 'Bearer '+ api_token}})
.then(response => {
//action
})
link: https://forum.vuejs.org/t/401-unauthorized-vuejs-laravel-and-passport/59770
or
postComment() {
axios.post('/api/posts/'+this.post.id+'/comment', {
api_token: this.user.api_token,
body: this.commentBox
})
but make sure that you have "user.api_token"
Some people just assume all has been configured right out of the box; but you need to:
Follow this Laravel documentation to gain api_token for all your users. Laravel api authentication
NOTE: When you register users, if users api_token in database is still being saved as NULL, go to the users model and add api_token to fillable array
//Model/User.php
protected $fillable = [
...
'api_token',
...
];
In your view layout app.blade.php create a meta for your token, just like your csrf:
//views/layout/app.blade.php
<!-- APIToken -->
<meta name="api_token" content="{{ Auth::user()->api_token }}">
Finally in your main.js or app.js; you can include it with every sent request
//resources/app.js
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'Authorization': 'Bearer '+ document.querySelector('meta[name="api_token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
This works and would help someone after all I've been through; meanwhile Laravel Passport and Sanctum are better recommendation for api authentication