ASP.NET Core Web API之Token验证 :https://blog.csdn.net/fengershishe/article/details/131388577
设置token有效时间:
1.在生成token时用IMemoryCache缓存,以token值为key,value为空,添加相对缓存时间。
2.添加TokenExtractorMiddleware,在Program添加启动中间件:app.UseMiddleware<TokenExtractorMiddleware>();
public class TokenExtractorMiddleware
{
private readonly RequestDelegate _next;
private readonly IMemoryCache _memoryCache;
public TokenExtractorMiddleware(RequestDelegate next, IMemoryCache memoryCache)
{
_next = next;
_memoryCache = memoryCache;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Headers.ContainsKey("Authorization"))
{
var authHeader = context.Request.Headers["Authorization"].ToString();
if (authHeader.StartsWith("Bearer "))
{
var token = authHeader.Substring("Bearer ".Length).Trim();
if (_memoryCache.Get(token) == null)
{
throw new Exception("Token is not found in cache.");
}
else
{
var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1));
_memoryCache.Set(token, "", cacheEntryOptions);
}
}
}
await _next(context);
}
}
标签:Bearer,memoryCache,JWT,Token,next,token,context From: https://www.cnblogs.com/wangtiantian/p/17896078.html