我试图在Core2.1的剃须刀页面上设置基于策略的授权。
我已经设置了策略,并用authorize属性装饰了剃须刀页面。我无法弄清楚我在做什么错或是否需要做其他事情,但是我无法获得该页面的授权。它总是给我
找不到该网址的网页:
localhost / ADENETCore / Account / AccessDenied?ReturnUrl =%2FADENETCore%2FContact
能给我指出正确的方向吗?
配置服务:
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();
配置:
app.UseAuthentication();
app.UseMvc();
政策要求:
public class MinimumAgeRequirement : IAuthorizationRequirement
{
public int MinimumAge { get; private set; }
public MinimumAgeRequirement(int minimumAge)
{
MinimumAge = minimumAge;
}
}
策略处理程序:
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MinimumAgeRequirement requirement)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
}
剃刀页面:
[Authorize(Policy = "AtLeast21")]
public class ContactModel : PageModel
它正在重定向到Account/AccessDenied
页
答案 0 :(得分:0)
您需要将授权处理程序添加为单例。
services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();