简体   繁体   中英

Add Requirements to Default [Authorize] policy

In ASP.Net Core there are custom policies that you can add to .AddAuthorization .

However, I need to add a requirement to the default policy because it will be used in every request. Is there a way I can do this without having to create a custom policy and always specifying it with [Authorize("Policy")] ?

services.AddAuthorization(options =>
            {
                options.AddPolicy("Unexpired",
                    policy => policy.Requirements.Add(new <requirement>));
            ...

Is there a way to make this policy part of the default?

In ASP.NET Core 5, it's probably the option 's DefaultPolicy you're looking for:

var unexpiredPolicy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser() // Remove if you don't need the user to be authenticated
    .AddRequirements(new MyRequirement())
    .Build();
services.AddSingleton<IAuthorizationHandler, MyRequirementHandler>();

services.AddAuthorization(options =>
{
    // This line can be omitted if you don't need to be
    // able to explicitly set the policy
    options.AddPolicy("Unexpired", unexpiredPolicy);

    // If no policy specified, use this
    options.DefaultPolicy = unexpiredPolicy;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM