You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.3 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using DS.Module.Core;
namespace DS.WMS.Gateway;
public class JwtSafeMiddleware
{
private readonly RequestDelegate _next;
public IConfiguration _configuration;
public JwtSafeMiddleware(RequestDelegate next, IConfiguration configuration)
{
_next = next;
_configuration = configuration;
}
public async Task Invoke(HttpContext context)
{
//表示如果RequestTokenServer1配置在网关下则访问它获取token的请求不走jwt校验哦
//if(!context.Request.Path.Value.StartsWith("/auth"))
if (context.Request.Method == "GET" || context.Request.Method == "POST")
{
// Console.WriteLine(context.Request.Path);
var path = context.Request.Path.ToString();
if (path.Contains("swagger") || path.Contains("login"))
{
//跳过swagger及login
}
else
{
string jwtStr = context.Request.Headers["Authorization"].FirstOrDefault();
// Console.WriteLine(jwtStr);
if (string.IsNullOrEmpty(jwtStr))
{
context.Response.StatusCode = 401; //401未授权
await context.Response.WriteAsync("token为空");
return;
}
//校验auth的正确性
var result = JwtHelper.SerializeJwt(jwtStr);
if (result == "expired")
{
context.Response.StatusCode = 401; //401未授权
await context.Response.WriteAsync("非法请求,参数已经过期");
return;
}
else if (result == "invalid")
{
context.Response.StatusCode = 401; //401未授权
await context.Response.WriteAsync("非法请求,未通过校验");
return;
}
else if (result == "error")
{
context.Response.StatusCode = 401; //401未授权
await context.Response.WriteAsync("非法请求,未通过校验");
return;
}
else
{
//表示校验通过
}
}
}
await _next.Invoke(context);
}
}