ly/MiddleWare/TokenValidationMiddleware.cs

75 lines
2.7 KiB
C#
Raw Normal View History

2025-03-29 14:50:23 +00:00
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)
{
2025-04-02 15:30:37 +00:00
try
2025-03-29 14:50:23 +00:00
{
2025-04-02 15:30:37 +00:00
// 排除不需要Token验证的API
if (IsExcludedPath(context.Request.Path))
2025-03-29 14:50:23 +00:00
{
2025-04-02 15:30:37 +00:00
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)
2025-03-29 14:50:23 +00:00
{
2025-04-02 15:30:37 +00:00
// 从Token中获取数据
var username = jsonToken.Claims.FirstOrDefault(claim => claim.Type == "sub")?.Value;
if (username != null)
2025-03-29 14:50:23 +00:00
{
2025-04-02 15:30:37 +00:00
if (await _redis.ExistsAsync(RedisKeyList.TokenUser(username)))
{
// Token和数据验证通过继续处理请求
await next(context);
return;
}
2025-03-29 14:50:23 +00:00
}
}
}
2025-04-02 15:30:37 +00:00
else
{
// Token不存在返回未授权
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid Token");
}
}
catch (Exception ex)
2025-03-29 14:50:23 +00:00
{
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid Token");
}
2025-04-02 15:30:37 +00:00
2025-03-29 14:50:23 +00:00
}
/// <summary>
/// 这是放不需要过滤的api地址
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private bool IsExcludedPath(PathString path)
{
// 根据实际情况定义不需要Token验证的API路径
2025-04-02 15:44:40 +00:00
string[] arry = { "login", "websocket" };
2025-03-29 14:50:23 +00:00
return arry.Any(s => path.Value.Contains(s));
// return path.StartsWithSegments("/api/public");
}
}
}