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.

71 lines
2.8 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;
using System.Security.Policy;
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")
{
var ignoreUrl = AppSetting.app(new string[] { "Cors", "IgnorePath" });
// Console.WriteLine(context.Request.Path);
var path = context.Request.Path.ToString().ToLower();
//if(ignoreUrl.Split(",", StringSplitOptions.RemoveEmptyEntries).ToArray().Contains(path))
if (path.Contains("swagger") || path.Contains("login") || path.Contains("tenantregister") || path.Contains("linkattach") || path.Contains("printtempfile")
|| path.Contains("favicon") || path.Contains("clientuserlogin") || path.Contains("addbookingstatuslog") || path.Contains("createbctaskjob"))
{
//跳过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);
}
}