【问题标题】:Custom AuthorizationHandler not being invoked未调用自定义 AuthorizationHandler
【发布时间】: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


    【解决方案1】:

    事实证明,我是在做假设,只是需要退后一步。如tutorial from Microsoft 中所述,处理程序是针对IAuthorizationHandler 接口注册的。

    本教程展示了如何创建单个需求的处理程序和多个需求的处理程序,但仅明确说明如何注册多个需求的处理程序。教程中没有明确说明该过程是相同的,并且根据我对 ASP.NET 的 DI 容器的经验,我认为我的解决方案是有道理的(因为一对一的处理程序实现了IAuthorizationHandler&lt;TRequirement&gt;,但是一个对多处理程序实现IAuthorizationHandler)。

    但是,无论如何都是一样的。我不确定 ASP.NET 如何解决这些依赖关系,因为任何数量的处理程序都将注册到 IAuthorizationHandler 接口,但无论如何它都可以工作。

    改变这个:

    services.AddTransient&lt;AuthorizationHandler&lt;NotLoggedInRequirement&gt;, NotLoggedInHandler&gt;();

    到这里:

    services.AddTransient&lt;IAuthorizationHandler, NotLoggedInHandler&gt;();

    有效地解决了问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2021-03-10
      • 2015-09-13
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多