Get the App
SLTechnology News&Howtos  ›  Development  › 

How to refresh JWT Token automatically by ASP.NET Core

Shulou Source: shulou.com Published: 2022-05-31 23:16:23 10月06日 Update

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)

Tags: Time knowledge inspection content article generation value function principle customer client that is easy to operate article easy to understand more look industry information information channel Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Docker Shulou Tech Info Redmi MySQL