【发布时间】:2021-05-17 21:39:35
【问题描述】:
我是第一次使用 Identity。我正在关注 Microsoft 的 Policy-based authorization tutorial,但是当我添加策略和要求时,永远不会调用该要求的处理程序。事实上,它的作用就像永远不会从 DI 中检索到处理程序(如果我注释掉将处理程序添加到 DI 容器的行,则应用程序的执行根本不会改变)。
NotLoggedInHandler 旨在确保某些页面仅由未登录的用户访问。处理程序只是成功并返回,因此该要求应始终通过:
public class NotLoggedInHandler : AuthorizationHandler<NotLoggedInRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotLoggedInRequirement requirement)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
}
但是当我访问受保护的 Razor 页面时,我会在日志输出中看到:
[xx:xx:xx INF] Authorization failed. These requirements were not met: WebApp.Policies.NotLoggedInRequirement
我已经弄乱了添加服务的顺序。 NotLoggedInHandler 是在services.AddAuthorization 之前还是之后注册似乎并不重要。
我的Startup.cs 文件如下所示:
public class Startup
{
// Other methods/ctor omitted
public void ConfigureServices(IServiceCollection services)
{
// Identity services omitted
// Set up Authentication
services.AddAuthentication(...);
// Set up Authorization
services.AddAuthorization(
options =>
{
options.AddPolicy(
"RequireAnonymous",
policy =>
{
policy.Requirements.Add(new NotLoggedInRequirement());
}
);
}
);
services.AddTransient<AuthorizationHandler<NotLoggedInRequirement>, NotLoggedInHandler>();
// Other services omitted, not related to Identity/auth
}
}
【问题讨论】:
标签: c# asp.net-core .net-core .net-5