Home > Back-end >  Tymon Jwtauth & Laravel - how to intercept unauthorised route and return 401 error?
Tymon Jwtauth & Laravel - how to intercept unauthorised route and return 401 error?

Time:01-05

I am using the Tymon JWT auth library to protect my API routes in laravel. All is working, however when an unauthenticated API request is made, it attempts to redirect to a login route. I would instead like to catch the unauthenticated exception and a 401 JSON response to the front end.

In regards to the code, it's more or less the same as the tutorial below: https://www.positronx.io/laravel-jwt-authentication-tutorial-user-login-signup-api/

Any help from someone who has already achieved this would be appreciated.

CodePudding user response:

If you send the Accept header as application/json this will cause the Exception Handler to return JSON when handling the Unauthorized Exception that the auth middleware will throw. You can see this in the unauthenticated method of Illuminate\Foundation\Exceptions\Handler.

If you don't let the server know you want JSON back in some way, and there are other ways, it will assume this is a normal web request and return a redirect to the 'login' page by default.

  •  Tags:  
  • Related