ly/MiddleWare/TokenValidationMiddleware.cs

75 lines
2.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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");
}
}
/// <summary>
/// 这是放不需要过滤的api地址
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private bool IsExcludedPath(PathString path)
{
// 根据实际情况定义不需要Token验证的API路径
string[] arry = { "login", "websocket", "uploadImg" };
return arry.Any(s => path.Value.Contains(s));
// return path.StartsWithSegments("/api/public");
}
}
}