tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.31k stars 1.55k forks source link

I want to customize the error handling when token expires or mismatches #1007

Open sudheerpal opened 7 years ago

sudheerpal commented 7 years ago

Below mentioned is the standard output when token is expired or mis-matched. { "error": { "message": "Token has expired", "status_code": 401 } }

While i want to return something like this, pasted below

return response()->json([ 'status' => 'error', 'message' => 'Token has expired' ], 401);

Its a simple way, how i am get user id from token $currentUser = JWTAuth::parseToken()->authenticate();

This is version for dependency, i am using. "php": ">=5.6.4", "laravel/framework": "5.3.*", "tymon/jwt-auth": "^0.5.9", "dingo/api": "1.0.x@dev",

derekmd commented 7 years ago

If you're using middleware classes BaseMiddleware and RefreshToken on your routes, update the App\Exceptions\Handler@render() method to handle UnauthorizedHttpException.

if ($e instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
    switch (get_class($e->getPrevious())) {
        case \Tymon\JWTAuth\Exceptions\TokenExpiredException::class:
            return response()->json([
                'status' => 'error',
                'message' => 'Token has expired'
            ], $e->getStatusCode());
        case \Tymon\JWTAuth\Exceptions\TokenInvalidException::class:
        case \Tymon\JWTAuth\Exceptions\TokenBlacklistedException::class:
            return response()->json([
                'status' => 'error',
                'message' => 'Token is invalid'
            ], $e->getStatusCode());
        default:
            break;
    }
}

Parsing request tokens at the controller-level on your own, these three classes have to be caught and handled for custom JSON responses:

fokosun commented 7 years ago

@derekmd thanks for this but what about the case of Token required?

alejoloe007jb commented 6 years ago

update the App\Exceptions\Handler@render() method to handle UnauthorizedHttpException.

public function render($request, Exception $e)
    {
        if ($e instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], $e->getStatusCode());
        }
        return parent::render($request, $e);
    }
zlanich commented 4 years ago

I can confirm @derekmd and @alejoloe007jb's solution worked for me, even as is in the ApiExceptionHandler in https://github.com/specialtactics/laravel-api-boilerplate

stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.