Add an authorization policy to ASP .NET core

ASP.NET core

Create a requirement class and a requirement handler


public class MyPolicyRequirement: IAuthorizationRequirement
    {
        public string Role {get; set;}
        
        public ManageUsersRequirement(string role)
        {
            Role = role;
        }
    }
    
    
public class MyPolicyRequirementHandler : AuthorizationHandler<MyPolicyRequirement>
    {
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ManageUsersRequirement requirement)
        {
            await Task.CompletedTask;

            if (context.User.IsInRole(requirement.Role))
            {
                context.Succeed(requirement);
                return;
            }
          
            context.Fail();  
        }
    }

Register the handler as a singleton in DI


services.AddSingleton<IAuthorizationHandler, MyPolicyRequirementHandler>();

Add the policy configuration


services.AddAuthorization((options) =>
      {
          options.AddPolicy("myPolicyName", new AuthorizationPolicy(
      	    new IAuthorizationRequirement[] { new MyPolicyRequirement("administrators") },
                new string[] { OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, IdentityConstants.ApplicationScheme }
            ));
      });

To use the policy add the [Authorize] attribute with the policy name


[Authorize(
      AuthenticationSchemes = $"Identity.Application,{OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme}",
      Policy = "myPolicyName"
)]

Post a Comment

Previous Post Next Post