using System.Text;
using Common;
using Extensions;
using Infrastructure;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Services;
//本命名空间暂时先不改,改动比较大2023年9月2日
namespace Filters
{
///
///
public class AuthorizationFilter : IAuthorizationFilter
{
private readonly ISysLoginService SysLoginService;
public AuthorizationFilter(ISysLoginService sysLoginService)
{
this.SysLoginService = sysLoginService;
}
///
///
///
public void OnAuthorization(AuthorizationFilterContext context)
{
var request = context.HttpContext.Request;
string content = "";
if(context.HttpContext.Request.Method.ToLower() == "get")
{
content = context.HttpContext.GetQueryString();
content = content.Substring(content.IndexOf("=") + 1);
content = Decrypt(content);
request.QueryString = new QueryString("value=" + content);
}
else if(context.HttpContext.Request.Method.ToLower() == "delete")
{
string path = request.Path.Value;
path = path.Substring(0, path.LastIndexOf("/") + 1) + Decrypt(path.Substring(path.LastIndexOf("/") + 1));
}
else
{
content = context.HttpContext.GetBody();
content = Decrypt(content);
//{"username":"admin","password":"000000"}
request.Body = new MemoryStream(Encoding.UTF8.GetBytes(content));
//验证登录接口
if(request.Path.Value.EndsWith("/oauth2/token"))
{
var scope = request.Query["scope"].ToString();
var grantType = request.Query["grant_type"].ToString();
bool checkLogin = SysLoginService.CheckLogin(scope, grantType, context.HttpContext.GetToken().Replace("Basic ", ""));
if(!checkLogin)
{
string msg = $"请求访问失败,无法访问系统资源";
context.Result = new JsonResult(ApiResult.Error(ResultCode.DENY, msg));
}
}
}
}
public string Decrypt(string str)
{
str = Encoding.UTF8.GetString(Convert.FromBase64String(str));
return Dbconn.AesDecrypt(str, Base.GlobalConstant.ApiKey, Base.GlobalConstant.ApiIv);
}
}
}