Multiple Authorization attributes on method

后端 未结 4 449
礼貌的吻别
礼貌的吻别 2020-12-08 06:12

I\'m having trouble specifying two separate Authorization attributes on a class method: the user is to be allowed access if either of the two attributes are true.

Th

4条回答
  •  悲&欢浪女
    2020-12-08 07:07

    I'm not sure how others feel about this but I wanted an OR behavior too. In my AuthorizationHandlers I just called Succeed if any of them passed. Note this did NOT work with the built-in Authorize attribute that has no parameters.

    public class LoggedInHandler : AuthorizationHandler
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        public LoggedInHandler(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }
    
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LoggedInAuthReq requirement)
        {
            var httpContext = httpContextAccessor.HttpContext;
            if (httpContext != null && requirement.IsLoggedIn())
            {
                context.Succeed(requirement);
                foreach (var req in context.Requirements)
                {
                    context.Succeed(req);
                }
            }
    
            return Task.CompletedTask;
        }
    }
    

    Supply your own LoggedInAuthReq. In startup inject these in services with

            services.AddAuthorization(o => {
                o.AddPolicy("AadLoggedIn", policy => policy.AddRequirements(new LoggedInAuthReq()));
                ... more here
            });
            services.AddSingleton();
            ... more here
    

    And in your controller method

        [Authorize("FacebookLoggedIn")]
        [Authorize("MsaLoggedIn")]
        [Authorize("AadLoggedIn")]
        [HttpGet("anyuser")]
        public JsonResult AnyUser()
        {
            return new JsonResult(new { I = "did it with Any User!" })
            {
                StatusCode = (int)HttpStatusCode.OK,
            };
        }
    

    This could probably also be accomplished with a single attribute and a bunch of if statements. It works for me in this scenario. asp.net core 2.2 as of this writing.

提交回复
热议问题