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 { /// /// API接口调用用户鉴权Filter /// 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().HttpContext; var repApiAuth = App.GetService>(); //未设置ApiCode时,使用方法名称 if (string.IsNullOrEmpty(apiUser.ApiCode)) { apiUser.ApiCode = actionDescriptor.MethodInfo.Name; } var auth = repApiAuth.Db.Queryable().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(); } } }