Sina
Sina

Reputation: 41

Handle jwt auth errors in laravel


I'm working on a rest api project.
I was struggling with an issue. As I get the token expiration error, the generated code will be something like this :

public function authenticate(Request $request){
    $this->checkForToken($request);

    try {
        if (! $this->auth->parseToken()->authenticate()) {
            throw new UnauthorizedHttpException('jwt-auth', 'User not found');
        }
    } catch (JWTException $e) {
        throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
    }
}

This code is written in this file :

vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php


How can I return this as a JSON type?

Upvotes: 2

Views: 8975

Answers (1)

Varol
Varol

Reputation: 1858

Catch that exception in your App\Exceptions\Handler class' render method and return a response formatted as json:

// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...

public function render($request, Exception $exception)
{   

  // if your api client has the correct content-type this expectsJson() 
  // should work. if not you may use $request->is('/api/*') to match the url.


  if($request->expectsJson()) 
  {

    if($exception instanceof UnauthorizedHttpException) {

      return response()->json('Unauthorized', 403);

    }

  }

  return parent::render($request, $e);

}

Upvotes: 5

Related Questions