Preface:
For security considerations, we can set a short expiration time for JWT Token, but this will cause the client to jump to the login interface frequently, which will have poor user experience.
The normal solution is to addrefresh_token
, the client uses refresh_token to actively refresh the JWT Token.
Here is a workaround,Automatically refresh JWT Token。
principle
We read each requestAuthorization
header, get the current requested JWT Token.
Check the expiration time of the current token. If it is within 30 minutes, then we generate a JWT token with a new expiration time and passX-Refresh-Token
Head back.
The client checkedX-Refresh-Token
header, replace the saved JWT token, and the next time you send the request, use the latest token.
accomplish
Create aMiddleware
,Its purpose is to check the JWT Token expiration time and generate a new token return:
public async Task InvokeAsync(HttpContext context) { JwtSecurityToken token = null; string authorization = ["Authorization"]; if (!(authorization) && ("Bearer ")) token = new JwtSecurityTokenHandler(). ReadJwtToken(("Bearer ".Length)); //Refresh Tokenif (token != null && > && (-30) <= ) { ("X-Refresh-Token", await RefreshTokenAsync(token)); } await _next(context); }
in conclusion
Of course, I recommend that you try to userefresh_token
, after all, this will be more secure.
This is the end of this article about Core automatically refreshing JWT Token. For more related Core automatic refreshing, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!