token 验证
This commit is contained in:
parent
dedaf3e0a3
commit
41dde067d2
|
|
@ -13,41 +13,50 @@ namespace LY.App.MiddleWare
|
|||
}
|
||||
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
|
||||
{
|
||||
// 排除不需要Token验证的API
|
||||
if (IsExcludedPath(context.Request.Path))
|
||||
try
|
||||
{
|
||||
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验证的API
|
||||
if (IsExcludedPath(context.Request.Path))
|
||||
{
|
||||
// 从Token中获取数据
|
||||
var username = jsonToken.Claims.FirstOrDefault(claim => claim.Type == "sub")?.Value;
|
||||
if (username != null)
|
||||
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)
|
||||
{
|
||||
if (await _redis.ExistsAsync(RedisKeyList.TokenUser(username)))
|
||||
// 从Token中获取数据
|
||||
var username = jsonToken.Claims.FirstOrDefault(claim => claim.Type == "sub")?.Value;
|
||||
if (username != null)
|
||||
{
|
||||
// Token和数据验证通过,继续处理请求
|
||||
await next(context);
|
||||
return;
|
||||
if (await _redis.ExistsAsync(RedisKeyList.TokenUser(username)))
|
||||
{
|
||||
// Token和数据验证通过,继续处理请求
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
else
|
||||
{
|
||||
// Token不存在,返回未授权
|
||||
context.Response.StatusCode = 401;
|
||||
await context.Response.WriteAsync("Unauthorized: Invalid Token");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Token不存在,返回未授权
|
||||
context.Response.StatusCode = 401;
|
||||
await context.Response.WriteAsync("Unauthorized: Invalid Token");
|
||||
}
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 这是放不需要过滤的api地址
|
||||
|
|
|
|||
Loading…
Reference in New Issue