I am developing a mobile application, and I realize that my token has a limited duration. I am using a Symfony server, which has a function to refresh me token:
/**
* @Route("/api/refresh", name="api_refresh")
*/
public function refreshTokenAction(Request $request)
{
if(!$request->headers->has('Authorization')) {
return;
}
$extractor = new AuthorizationHeaderTokenExtractor(
'Bearer',
'Authorization'
);
$token = $extractor->extract($request);
$encoder = $this->get('lexik_jwt_authentication.encoder');
$data = $encoder->decode($token);
if(!$data){
return;
}
$username = $data['mail'];
$user = $this->getDoctrine()->getRepository('AppBundle:Benevole')
->findOneBy(['mail' => $username]);
$token = $this->get('lexik_jwt_authentication.encoder')
->encode(['mail' => $user->getMail()]);
// Return genereted tocken
return new JsonResponse(['token' => $token]);
}
I use this server with an application in AngularJS, in which I call my server in this way:
var refreshToken = function(idPatient){
var token = window.localStorage.getItem('token'); // current valid token
return $http({
method : 'GET',
url : url + '/refresh',
headers : {Authorization : 'Bearer ' + token},
}).then(function(result) {
console.log(result.data);
return result.data;
});
};
When I test my function refresh token, clicking a button, it works, the token is refreshed.
I would like to know how I can refresh my token, this automatically, so that the user does not have to disconnect each time, because it is rather restrictive ^^ Should I check my token every time ? Should I put several conditions for the application to find this every time ?
You should accept only valid (and non-expired) tokens for refreshment. Assume that it's responsability of the client to refresh the tokens before the expiration date indicated in the exp
claim.
You can call the function to refresh the token periodically, while the use is active in the page.
To avoid a token from being refreshed indefinitely, you could, for example, keep the track of the token refreshment by adding two claims to your token (the claim names are up to you):
refreshLimit
: Indicates how many times the token can be refreshed.refreshCount
: Indicates how many times the token has been refreshed.So only refresh the token if the following conditions are true:
exp >= now
).refreshCount < refreshLimit
).And when refreshing the token:
exp = now + some-amount-of-time
).refreshCount++
).Once the token is signed and the signature is verified on server side, the content of the token cannot be tampered by the client.