locked
Resource based authorization, passing every parameters to authorization handler RRS feed

  • Question

  • User-81839486 posted

    I'm new to resource based authorization. I did it with help of link. I want to allow editing licence only by admin or user who created it. I wonder if it is ok to pass to authorization handler not only licence user id but also current user id and IsAdmin bool and check it inside handler.

    public async Task<IActionResult> OnGetAsync()
    {
    
    var authorize = new AuthorizationAuthor { CurrentUserId = currentUserId, 
    LicenceUserId= licenceUserId,
    IsAdmin = ((ClaimsIdentity)User.Identity).HasClaim("IsAdmin", "true") };
    
    var authorizationResult = await authorizationService.AuthorizeAsync(User, authorize, "EditLicencje");
    
    if (authorizationResult.Succeeded)
    {
    
    //do sth
    
    }
    
    }

    services.AddAuthorization(options =>
                {
                    options.AddPolicy("EditLicencje", policy =>
                        policy.Requirements.Add(new SameAuthorRequirement()));
                });
                services.AddSingleton<IAuthorizationHandler, LicenceAuthorizationHandler>();

        public class AuthorizationAuthor
        {
            public string LicenceUserId { get; set; }
            public string CurrentUserId { get; set; }
            public bool IsAdmin { get; set; }
        }

    public class LicenceAuthorizationHandler : AuthorizationHandler<SameAuthorRequirement, AuthorizationAuthor>
        {
            protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                           SameAuthorRequirement requirement,
                                                           AuthorizationAuthor resource)
            {
                if (resource.CurrentUserId == resource.LicencjaUserId || resource.IsAdmin)
                {
                    context.Succeed(requirement);
                }
    
                return Task.CompletedTask;
            }
        }
    
        public class SameAuthorRequirement : IAuthorizationRequirement { }






    Sunday, August 23, 2020 3:06 PM

All replies

  • User711641945 posted

    Hi karol,

    I wonder if it is ok to pass to authorization handler not only licence user id but also current user id and IsAdmin bool and check it inside handler.

    It seems your code could satisfy your requirement.Did you have any problems?

    Best Regards,

    Rena

    Monday, August 24, 2020 6:31 AM