using learun.operat;
using learun.util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Threading.Tasks;
namespace learun.webapi
{
///
/// 版 本 Learun-ADMS-Core 力软管理后台
/// Copyright (c) 2019-present 力软信息技术(苏州)有限公司
/// 创建人:tobin
/// 日 期:2019.09.11
/// 描 述:权限中间件
///
public class AuthorizeMiddleware
{
private readonly RequestDelegate _next;
private readonly IOperator _operator;
///
/// 构造方法
///
/// 请求委托
/// 验证登录信息方法
public AuthorizeMiddleware(RequestDelegate next, IOperator ioperator)
{
_next = next;
_operator = ioperator;
}
///
/// 执行
///
/// 请求连接
///
public async Task Invoke(HttpContext httpContext)
{
//string url = SetUrl(httpContext);
var endpoint = httpContext.GetEndpoint();
if (endpoint != null && endpoint.Metadata.GetMetadata() == null)
{
// 获取请求值
if (!httpContext.Request.Headers["token"].IsEmpty())
{
string token = httpContext.Request.Headers["token"].ToString();
var res = _operator.DecodeToken(token);
if (res == "TokenExpiredException")
{
await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "登录信息过期" });
return;
}
else if (res == "SignatureVerificationException")
{
await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "非法密钥" });
return;
}
else
{
var payload = res.ToObject();
ContextHelper.SetItem("account", payload.Account);
ContextHelper.SetItem("userId", payload.UserId);
ContextHelper.SetItem("userName", payload.UserName);
}
}
else
{
await RespondWithJson(httpContext.Response, new ResParameter { code = ResponseCode.nologin, info = "权限验证失败" });
return;
}
}
else
{
if (httpContext.Request.Query.ContainsKey("lraccount"))
{
string account = httpContext.Request.Query["lraccount"];
ContextHelper.SetItem("account", account);
}
}
await _next(httpContext);
return;
}
///
/// 返回请求信息
///
/// 返回头
/// 数据
///
private async Task RespondWithJson(HttpResponse response, object data)
{
response.StatusCode = 200;
response.ContentType = "application/json;charset=utf-8";
await response.WriteAsync(data.ToJson(), new UTF8Encoding(false));
}
}
}