I want to add custom policies for two-step authorization, so after the first step user will have access to second step, and after that to everything. When I had one policy everything worked fine, but when I added another I started getting this error. How I add policies:
AuthorizationOptions authOptions = new AuthorizationOptions();
authOptions.AddPolicy("FirstStepCompleted", policy => policy.RequireClaim("FirstStepCompleted"));
authOptions.AddPolicy("Authorized", policy => policy.RequireClaim("Authorized"));
services.AddAuthorization(o => o = authOptions);
When I had one policy, I added it like this:
services.AddAuthorization
(
options => options.AddPolicy("FirstStepCompleted",
policy => policy.RequireClaim("FirstStepCompleted"))
);
What am I doing wrong?
UPD1. Forgot the exception:
An unhandled exception occurred while processing the request. InvalidOperationException: The AuthorizationPolicy named: 'FirstStepCompleted' was not found. Microsoft.AspNetCore.Authorization.AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProvider policyProvider, IEnumerable authorizeData)
The AddAuthorization
call takes a delegate that will receive an instance of AuthorizationOptions
to configure. In your failing example, you are attempting to replace this existing instance of AuthorizationOptions
with a new one that you've created above (authOptions
), which has no real effect (see Jon Skeet's answer for more information on reassigning parameters). Ultimately, this means you're not adding any policies.
If you want to add multiple policies in the delegate, you can use the following:
services.AddAuthorization(o =>
{
o.AddPolicy("FirstStepCompleted", policy => policy.RequireClaim("FirstStepCompleted"));
o.AddPolicy("Authorized", policy => policy.RequireClaim("Authorized"));
});