Im following a tutorial on using JWT-Auth with Laravel, its telling me to create a middleware with the following handle()
method;
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return $this->returnResponse('Token is Invalid');
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return $this->returnResponse('Token is Expired');
}else{
return $this->returnResponse('Authorization Token not found');
}
}
return $next($request);
}
Then in my controller create a method called getAuthenticatedUser()
with the following code;
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return $this->errorNotFound('User not found');
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return $this->errorWrongArgs('Token is Expired');
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return $this->errorWrongArgs('Token is Invalid');
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return $this->errorNotFound('Authorization Token not found');
}
return $this->respondWithItem($user, new UserTransformer);
}
The problem im having is;
Isn't middleware always run BEFORE a request? thats the point of it. So the try catch in the getAuthenticatedUser method is redundant and doubling up on code. If i changed the getAuthenticatedUser()
to the following, wouldn't that be doing the exact same thing;
public function getAuthenticatedUser()
{
if (! $user = JWTAuth::parseToken()->authenticate()) {
return $this->errorNotFound('User not found');
}
return $this->respondWithItem($user, new UserTransformer);
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire