【问题标题】:Authentication with custom implementation of IAuthorizationPolicyProvider in dotnet core 3.1在 dotnet core 3.1 中使用 IAuthorizationPolicyProvider 的自定义实现进行身份验证
【发布时间】:2023-04-04 04:30:01
【问题描述】:

我已经按照here 提供的文档实现了一个自定义 IAuthorizationPolicyProvider,但是当我调试并到达处理程序并查看 context.User 对象时,我看到 IsAuthenticated 或 context.User.IsInRole 等属性是 false/空的。我的应用程序配置了 jwt 令牌授权,并且我已确认该令牌确实包含角色有效负载数据中的值,但它似乎在到达处理程序以供我使用这些值之前进行身份验证。有人可以帮助我了解操作顺序,或者我如何能够逐步完成实际发生的身份验证吗?

我的 Startup.cs 中有身份验证和授权:

services.AddAuthentication(sharedOptions =>
{
    sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})

services.AddAuthorization(options =>
{
    var defaultAuthorizationBuilder = new AuthorizationPolicyBuilder("Bearer");
    defaultAuthorizationBuilder = defaultAuthorizationBuilder.RequireAuthenticatedUser();
    options.DefaultPolicy = defaultAuthorizationBuilder.Build();
}

services.AddSingleton<IAuthorizationPolicyProvider, MyCustomPolicyProvider>();
services.AddSingleton<IAuthorizationHandler, MyCustomHandler>();

【问题讨论】:

  • 服务的调用顺序无关紧要。你在 AddAuthentication() 之后添加了AddJwtBearer() 吗?您是否在请求管道中调用app.UseAuthentication();app.UseAuthorization();?请注意这里的顺序确实很重要。
  • 是的。上面的代码只是一个 sn-p——我在 AddAuthentication 之后调用的自定义方法中调用 AddJwtBearer。我实际上有几个自定义身份验证方案。我在 Configure 方法中以正确的顺序调用 app.UseAuthentication() 和 app.UseAuthorization()。

标签: c# asp.net-core authentication authorization


【解决方案1】:

经过大量修改后,我想分享我学到的答案,以及实施自定义策略提供程序如何工作的更广泛问题。在 Startup.cs 中使用 AddAuthentication 和 AddAuthorization 时,这将作为设置默认授权策略提供程序时使用的策略设置,例如:

public YourAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options)
{
    this.BackupPolicyProvider = new DefaultAuthorizationPolicyProvider(options);
}

对我来说,我默认使用这个后备策略提供程序:

public Task<AuthorizationPolicy> GetDefaultPolicyAsync()
{
    return this.BackupPolicyProvider.GetDefaultPolicyAsync(); //this is the default policy established in Startup.cs
}

(注意:我发现一些令人困惑的东西,并且没有很多清晰的文档:DefaultPolicy vs FallbackPolicy,尤其是因为在撰写本文时,GetFallbackPolicyAsync 最近成为一种在实现 IAuthorizationPolicyProvider 时需要实现的方法。DefaultPolicy:当应用 [Authorize] 属性时,这是要使用的策略。当提供 no 策略时,调用 GetFallbackPolicyAsync。)

我在构建自定义策略时缺少的是在 AuthorizationPolicyBuilder 中指定我希望策略使用的身份验证方案。我现在意识到它在文档中,但没有特别指出,所以我错过了它:

public Task<AuthorizationPolicy> GetPolicyAsync(string policyName)
{
    if (//some check on your policy name)
    {
        var policy = new AuthorizationPolicyBuilder(//what scheme to use for authentication);
        // your requirements
        return Task.FromResult(policy.Build());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2016-07-09
    相关资源
    最近更新 更多