Search code examples
c#asp.net-coreasp.net-core-2.0authorize-attribute

c# .Net Core 2.1 Authorize Attribute - Default Claims


When using the [Authorize] Attribute (without specifying a policy), is there a way to set a required claim on the default policy?

The point being i would like it to require a claim to authorize, but i don't want to have to explicitly set the policy for the controllers. I'd rather just have [Authorize] not [Authorize(Policy = "something")]

Another way to ask this is, is it possible to add a claim to the default policy?

Thanks in advance for any and all ideas and opinions.


Solution

  • You can override default policy in startup

    services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
                                          .RequireClaim("CLAIM")
                                          .Build();
    });
    

    Also if you want to authorize by some custom policy and avoid writing the policy multiple times, you can create a new authorize attribute

    public class AuthorizePolicyAttribute : AuthorizeAttribute
    {
        public AuthorizePolicyAttribute()
        {
            Policy = "CustomPolicy";
        }
    }