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.

66 lines
3.4 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 EntrustSettle.Common;
using EntrustSettle.Common.Const;
using EntrustSettle.IRepository.Base;
using EntrustSettle.Model.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;
namespace EntrustSettle.Filter
{
/// <summary>
/// API接口调用用户鉴权Filter
/// </summary>
public class ApiUserFilter : IAsyncActionFilter
{
public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
var attrAllowAnonymous = actionDescriptor.EndpointMetadata.FirstOrDefault(x => x.GetType() == typeof(AllowAnonymousAttribute));
var attrApiUser = actionDescriptor.EndpointMetadata.FirstOrDefault(x => x.GetType() == typeof(ApiUserAttribute));
if (attrAllowAnonymous != null && attrApiUser != null)
{
var apiUser = attrApiUser as ApiUserAttribute;
if (context.HttpContext.Request.Headers.ContainsKey(CommonConst.API_USER_HEADER_KEY)
&& context.HttpContext.Request.Headers.ContainsKey(CommonConst.API_USER_HEADER_SECRET))
{
var key = context.HttpContext.Request.Headers[CommonConst.API_USER_HEADER_KEY].ToString();
var secret = context.HttpContext.Request.Headers[CommonConst.API_USER_HEADER_SECRET].ToString();
var httpContext = App.GetService<IHttpContextAccessor>().HttpContext;
var repApiAuth = App.GetService<IBaseRepository<ApiAuth>>();
//未设置ApiCode时使用方法名称
if (string.IsNullOrEmpty(apiUser.ApiCode))
{
apiUser.ApiCode = actionDescriptor.MethodInfo.Name;
}
var auth = repApiAuth.Db.Queryable<ApiAuth>().Where(x => x.ApiKey == key
&& x.ApiSecret == secret
&& x.ApiCode == apiUser.ApiCode
&& x.IsDisable == false).First();
if (auth != null && (!auth.ExpireDate.HasValue || auth.ExpireDate > DateTime.Now))
{
ClaimsIdentity identity = new ClaimsIdentity("AuthenticationTypes.Federation");
identity.AddClaim(new Claim(type: ClaimConst.LOGIN_ID, value: auth.UserId));
identity.AddClaim(new Claim(type: ClaimConst.LOGIN_NAME, value: auth.UserName));
identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYID, value: auth.CompanyId));
identity.AddClaim(new Claim(type: ClaimConst.LOGIN_COMPANYNAME, value: auth.CompanyName));
identity.AddClaim(new Claim(type: ClaimConst.LOGIN_MOBILE, value: ""));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
httpContext.User = claimsPrincipal;
return next();
}
}
throw new Exception("无权调用!请检查授权或联系管理员。");
}
return next();
}
}
}