Instead of checking whether my JWT Token has expired on every query, I'd like to check it only upon the first initialization of the app in main
and then automatically refresh it every 55 minutes.
Here's my refresh function which I invoke at the top of my Widget tree ;
void main() async {
await refreshToken()
};
And here's the refreshToken code;
Future<String?> refreshToken() async {
String? refreshToken = await getCryptRefresh(); //gets refresh token from an encrypted box
final http.Response response =
await http.post(Uri.parse('http://example.com/refresh'),
headers: <String, String>{'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(<String?, dynamic>{
'email': currentemail,
'id': currentuserid,
'refreshToken': refreshToken
}),
);
if (response.body.contains('token')) {
Map<String, dynamic> refreshMap = json.decode(response.body);
String token = refreshMap['token'];
putCryptJWT(token); // stores new token in encrypted Hive box
print("token renewed = " + token);
Timer(Duration(minutes: 55), () {
refreshToken();
});
return token;
} else {
String noresponse = 'responsebody doesnt contain token';
print(noresponse);
}
}
Android studio first gave me a null error with a red line under refreshToken()
and suggested a nullcheck !
. But once I did that I gave me this error;
The expression doesn't evaluate to a function, so it can't be invoked.
It suggested I remove the parenthesis in the getter invocation. So I removed both the parenthesis and the nullcheck to just simply refreshToken
;
But it doesn't run every 55 minutes as I hoped.
I'd rather not check the expiry upon every query. Both my JWTToken and its RefreshToken are stored in an encrypted Hive box. Hence checking every query seems a bit intensive.
I don't know if this is preferable to using Dio, but I simply did this for all HTTP post requests;
It seems to work well.