using LY.App.Common.Redis;
using StackExchange.Redis;
using System.IdentityModel.Tokens.Jwt;
namespace LY.App.MiddleWare
{
public class TokenValidationMiddleware : IMiddleware
{
private RedisService _redis;
public TokenValidationMiddleware(RedisService redisHelper)
{
_redis = redisHelper;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
try
{
// 排除不需要Token验证的API
if (IsExcludedPath(context.Request.Path))
{
await next(context);
return;
}
// 获取Token
var token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (!string.IsNullOrEmpty(token))
{
// 验证Token是否有效
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(token) as JwtSecurityToken;
if (jsonToken != null)
{
// 从Token中获取数据
var username = jsonToken.Claims.FirstOrDefault(claim => claim.Type == "sub")?.Value;
if (username != null)
{
if (await _redis.ExistsAsync(RedisKeyList.TokenUser(username)))
{
// Token和数据验证通过,继续处理请求
await next(context);
return;
}
}
}
}
else
{
// Token不存在,返回未授权
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid Token");
}
}
catch (Exception ex)
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid Token");
}
}
///
/// 这是放不需要过滤的api地址
///
///
///
private bool IsExcludedPath(PathString path)
{
// 根据实际情况定义不需要Token验证的API路径
string[] arry = { "login", "websocket" };
return arry.Any(s => path.Value.Contains(s));
// return path.StartsWithSegments("/api/public");
}
}
}