Laravel 5: activate API token guard and print “Unauthorized” instead of login redirect

In Laravel 5, I wrap my API routes in a route group like this:

Notice that I use auth:api and throttle on my middleware array.

auth:api turns on the auth middleware with API token as guard, while throttle activates rate limiter for APIs.

To get started with API token authentication, you may read https://gistlog.co/JacobBennett/090369fbab0b31130b51.

I followed the same tutorial to set mine up, but had this issue: Upon using invalid api_token or no token at all, I am redirected to the /login route, which in my case is a currently nonexistent route.

As instructed by the guide, I already edited my app/Http/Middleware/Authenticate.php file to add the || $request->wantsJson() condition, but my API routes still redirected to /login route upon detection of invalid api_token.

The solution

What I did was add another condition: || $guard == "api"

And now, my app/Http/Middleware/Authenticate.php file looks like this:

Catzie

A Filipino who is a mobile & web developer on weekdays, and a baker on weekends. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Follow on Twitter: @catzie

Leave a Reply

Your email address will not be published. Required fields are marked *