DEV Community

Victor Basumatary
Victor Basumatary

Posted on

Today I Fixed...

I have been working on a website using Laravel 7 for a while. This is the first time I'm building something with Laravel. We use Passport for authentication and of course, API calls are authenticated with it as well.

So the bug I encountered was I wasn't able to call my API. I am using the "auth:api" middleware on my controller to authenticate my API requests. Ideally my request gets through, required I was authenticated and authorized, but instead I was always redirected to the login page.

Initially I thought something was wrong with the middleware but quickly ruled it out. In another part of the website API requests made through just fine. Clearly the middleware was working. Besides it's the middleware's correct behavior to redirect you to the login page if you aren't authenticated.

The only real difference between these two pieces of code was that in one I used axios to make the API request and in the other I used fetch(). The fetch() call was failing.

After a little digging and attentive reading of the docs (this was the hardest part of the whole process for me) I finally figured it out.

Recall that I am using Passport for authentication. It handles API authentication too out of the box. The way it does it is:

  1. When you login an api token is made for you. This is sent back as a cookie (laravel-token by default).

  2. Another cookie called xsrf-token is also sent back.

  3. When making an API request the xsrf-token must be decoded using decodeURIComponent() and sent back as the x-xsrf-token header

axios would do step 3 automatically, I don't know how or why. When you use fetch() you need to do step 3 manually.

Top comments (2)

Collapse
 
dendihandian profile image
Dendi Handian

the alternative way is to use these headers in the client's request:

Content-Type: application/json
Accept: application/json
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mustafapc19 profile image
mustafapc19

Debugging laravel issues sucks. Or is there any better way to debug. So many times the error logs are so un helpful. I don't know if I was at fault tho