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:

Related Posts:

Posts that may be related to "Laravel 5: activate API token guard and print “Unauthorized” instead of login redirect":

Catzie

A Filipino programmer with a variety of interests such as baking, singing, making up silly song/rap lyrics, K-pop, drawing, creating unique dessert flavors, obsessing about finding out how some things works, board games, anime, video games, and forgetting things that usually go in her long list of interests. Running small-time online dessert shops Cookies PH and Catzie's Cakery.

Leave a Reply

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