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() 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:
When you login an api token is made for you. This is sent back as a cookie (laravel-token by default).
Another cookie called xsrf-token is also sent back.
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)
the alternative way is to use these headers in the client's request:
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