1

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.

2
  • 2
    Show the code of the controller and the middleware. Also is this an api? Commented Sep 24, 2019 at 7:24
  • 1
    how is your authentication working ? coockie session ? jwt ? Commented Sep 24, 2019 at 7:25

2 Answers 2

2

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"

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.