I have set up Laravel with jwt (using jwt-auth). In my Kernel.php - $routeMiddleware I have added :
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class
As I understand it 'jwt.refresh' will automatically refresh / create a new token for the user for each request.
In my single page ajax app I need to check if the user is logged in so I have added a route that calls this function:
public function isAuthenticated() {
$token = JWTAuth::getToken();
if(!$token){
throw new JWTException('Token not provided');
}
try{
$token = JWTAuth::refresh($token);
}catch(TokenInvalidException $e){
throw new AccessDeniedHttpException('The token is invalid');
}
return $this->response->withArray(['token'=>$token]);
}
The problem is that when isAuthenticated() is called the JWTAuth::refresh($token) call fails.
I guess it has something to do with that the token is refreshed.
What I want to do is to return true if the client's token is valid. Is there a way to do this?
Removing 'jwt-refresh' seems to not solve the issue for us.
Thank you in advance!
My first observation is, where is the token stored? Is it parsed with the request? Because I believe that if your app uses jwt with api, then each request should have a token to signify a logged in user so something like this would be helpful:
try {
if (! $token = JWTAuth::parseToken()) {
//throw an exception
}
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
//throw an exception
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
//throw an exception
} else if ( $e instanceof \Tymon\JWTAuth\Exceptions\JWTException) {
//throw an exception
}else{
//throw an exception
}
}
If successfully parsed from the request, then:
$user = JWTAuth::toUser($token);
see: https://github.com/tymondesigns/jwt-auth/wiki/Authentication
With your example code, if the token is not set - nothing is retrieved. However, if you want session based authentication, why not use the default authentication from Laravel.
Hope this helps :)
You can get the current user related to token and check if not null:
$user = JWTAuth::setToken($token)->toUser();
if($user == null){
abort(401);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With