aspnetcore 认证和授权


    public class EAuthenticationHandler : AuthenticationHandler
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public EAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IHttpContextAccessor httpContextAccessor)
            : base(options, logger, encoder, clock)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        protected override async Task HandleAuthenticateAsync()
        {
            Console.WriteLine("HandleAuthenticateAsync ");
            const string headerKey = "authorization";
            var header = _httpContextAccessor.HttpContext.Request.Headers;
            if (header.ContainsKey(headerKey))
            {
                var claims = new List { new Claim(headerKey, header[headerKey]) };
                var identity = new ClaimsIdentity(claims, headerKey);
                var identities = new List { identity };
                var principal = new ClaimsPrincipal(identities);
                var ticket = new AuthenticationTicket(principal, headerKey);
                return AuthenticateResult.Success(ticket);
            }
            return AuthenticateResult.NoResult();
        }

        protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Console.WriteLine("HandleChallengeAsync ");
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status401Unauthorized;
            await Response.WriteAsync(JsonConvert.SerializeObject(new { Code = "401"}));
        }

        protected override async Task HandleForbiddenAsync(AuthenticationProperties properties)
        {
            Console.WriteLine("HandleForbiddenAsync ");
            Response.ContentType = "application/json";
            Response.StatusCode = StatusCodes.Status403Forbidden;
            await Response.WriteAsync(JsonConvert.SerializeObject(new { Code = "403" }));
        }
    }

    public class EAuthorizationService : DefaultAuthorizationService, IAuthorizationService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EAuthorizationService(IAuthorizationPolicyProvider policyProvider, IAuthorizationHandlerProvider handlers, ILogger logger, IAuthorizationHandlerContextFactory contextFactory, IAuthorizationEvaluator evaluator, IOptions options, IHttpContextAccessor httpContextAccessor) : base(policyProvider, handlers, logger, contextFactory, evaluator, options)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public async new Task AuthorizeAsync(ClaimsPrincipal user, object resource, IEnumerable requirements)
        {
            Console.WriteLine("EAuthorizationService -- requirements");
            var header = _httpContextAccessor.HttpContext.Request.Headers;
            const string OpenId = "OpenId";
            if (header.ContainsKey(OpenId))
            {
                Console.WriteLine("OpenId = " + header[OpenId]);
                var isExist = true;// 缓存中判断是否有效
                if (isExist)
                {
                    return AuthorizationResult.Success();
                }
                return AuthorizationResult.Failed();
            }
            else
            {
                Console.WriteLine("base.AuthorizeAsync");
                var res = await base.AuthorizeAsync(user, resource, requirements);
                return res;
            }
        }

        public new Task AuthorizeAsync(ClaimsPrincipal user, object resource, string policyName)
        {
            Console.WriteLine("EAuthorizationService -- policyName");
            var res = base.AuthorizeAsync(user, resource, policyName);
            return res;
        }
    }
            services.AddHttpContextAccessor();
            services.AddAuthentication(x =>
            {
                x.AddScheme("e", "e");
                x.DefaultAuthenticateScheme = "e";
                x.DefaultChallengeScheme = "e";
            });
            services.AddAuthorization();
            services.AddSingleton();