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",
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:
Tymon\JWTAuth\Exceptions\JWTExceptionTymon\JWTAuth\Exceptions\TokenExpiredExceptionTymon\JWTAuth\Exceptions\TokenInvalidException@derekmd thanks for this but what about the case of Token required?
update the AppExceptionsHandler@render() method to handle UnauthorizedHttpException.
Handler.php
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);
}
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
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.
Most helpful comment
update the AppExceptionsHandler@render() method to handle UnauthorizedHttpException.
Handler.php 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); }