I trying to set up policy-based authorization on razor pages on Core2.1.
I have set up the policy and decorated the razor page with the authorize attribute. I cannot figure what am I doing wrong or if something else needs to be done, but I cannot get the page to authorize. It always gives me
No web page was found for the web address:
localhost/ADENETCore/Account/AccessDenied?ReturnUrl=%2FADENETCore%2FContact
Can you please point me in the right direction?
ConfigureServices:
services.AddAuthorization(options =>
{
options.AddPolicy("AtLeast21", policy =>
policy.Requirements.Add(new MinimumAgeRequirement(21)));
});
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact", "AtLeast21"); // with policy
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();
Configure:
app.UseAuthentication();
app.UseMvc();
Policy Requirement:
public class MinimumAgeRequirement : IAuthorizationRequirement
{
public int MinimumAge { get; private set; }
public MinimumAgeRequirement(int minimumAge)
{
MinimumAge = minimumAge;
}
}
Policy Handler:
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MinimumAgeRequirement requirement)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
}
Razor Page:
[Authorize(Policy = "AtLeast21")]
public class ContactModel : PageModel
It is redirecting to the Account/AccessDenied
page
You need to add your authorization handlers as singletons.
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
For more info check: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments