Reputation: 846
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.
Upvotes: 3
Views: 1814
Reputation: 349
In order to prevent a false positive error (i.e. You forget to put the [Authorize] attribute in one of your hundreds of action methods or controllers and a skilled hacker somehow reached that endpoint) you can also add a convention to your controllers so that they are automatically having the [Authorize] attribute. In case you really do not need the authorization on some action method or controller, then you can use [AllowAnonymous] attribute for it.
First you have to create a new authorizaton policy and add it to your services in your Startup.cs class under ConfigureServices method:
services.AddAuthorization(o => {
o.AddPolicy("authwithsomepolicy", p =>
{
p.RequireAuthenticatedUser();
p.RequireClaim("MYPOLICY");
});
});
Then you create a new class that extends IControllerModelConvention and makes the automatization for that policy for all of your controllers:
public class AddAuthorizeFilters : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
controller.Filters.Add(new AuthorizeFilter("authwithsomepolicy"));
}
}
And finally in your Startup.cs class you can add this convention to your Mvc system (again under ConfigureServices method):
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(setupAction =>
{
setupAction.Conventions.Add(new AddAuthorizeFilters ());
});
}
Upvotes: 2
Reputation: 14995
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";
}
}
Upvotes: 5