How to refresh JWT Token automatically by ASP.NET Core
This article mainly introduces ASP.NET Core how to achieve automatic refresh JWT Token related knowledge, the content is detailed and easy to understand, simple and fast operation, has a certain reference value, I believe that everyone after reading this ASP.NET Core how to achieve automatic refresh JWT Token article will have a harvest, let's take a look at it.
Principle
We read the Authorization header of each request and get the JWT Token of the current request.
Check the expiration time of the current token. If it is within 30 minutes, then we generate a JWT Token with the new expiration time and return it through the X-Refresh-Token header.
When the client checks the X-Refresh-Token header, it replaces the saved JWT Token, and the next time it sends the request, it will use the latest token.
Realize
Create a Middleware that checks the JWT Token expiration time and generates a new token return:
Public async Task InvokeAsync (HttpContext context) {JwtSecurityToken token = null;string authorization = context.Request.Headers ["Authorization"]; if (! string.IsNullOrEmpty (authorization) & & authorization.StartsWith ("Bearer")) token = new JwtSecurityTokenHandler () .ReadJwtToken ("Bearer" .length); / / Refresh Tokenif (token! = null&& token.ValidTo > DateTime.UtcNow&& token.ValidTo.AddMinutes (- 30)