首页 > 解决方案 > 基于策略的授权 - Auth0 身份验证 - 始终返回 Forbidden 403

问题描述

我正在使用 Auth0 在我的后端 API 服务器中获得一些身份验证和授权。Auth0 使用角色 + 权限的系统,这与此处描述的策略概念兼容 - https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-3.1

在用户方面,我没有问题,收集令牌。当我研究令牌时,我注意到必要的范围正在通过。

{
  "iss": "https://randomquoteexperimental.us.auth0.com/",
  "sub": "removedonpurpose",
  "aud": [
    "https://thechalakas.com",
    "https://randomquoteexperimental.us.auth0.com/userinfo"
  ],
  "iat": 1601906519,
  "exp": 1601992919,
  "azp": "removedonpurpose",
  "scope": "openid profile email",
  "permissions": [
    "read:penquotes"
  ]
}

此外,在同一个 API 服务器上,没有范围的端点、没有令牌和有令牌的端点都可以正常返回。因此,API 服务器很好,并且可以很好地读取无范围授权。

在我的 API 服务器上,我有以下内容。这是我的配置服务。

    // Register the scope authorization handler
    services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();

    services.AddAuthorization(options =>
    {
        //TODO1 - similar to above , migrate this also to appsettings.json
        options.AddPolicy("capquotes", policy => policy.Requirements.Add(new HasScopeRequirement("read:capquotes", "https://randomquoteexperimental.us.auth0.com/")));
        options.AddPolicy("penquotes", policy => policy.Requirements.Add(new HasScopeRequirement("read:penquotes", "https://randomquoteexperimental.us.auth0.com/")));
    });

而且,这是一个简单的端点,我正在尝试访问。

[HttpGet]
[Route("PenScope1")]
[Authorize(Policy = "penquotes")]
public ActionResult<GeneralAPIResponse> PenScope1()
{
    var tempItemViewModel = new GeneralAPIResponse();
    var tempString1 = "You have the PEN Scope as per the rules"; 
    tempItemViewModel.ListOfResponses.Add(tempString1);
    return tempItemViewModel;
}

我已遵循官方指南,可在此处获得 - https://auth0.com/docs/quickstart/backend/aspnet-core-webapi/01-authorization#configure-the-sample-project

由于令牌具有正确的权限,并且它们是由在 Auth0 系统上配置的 API 服务器发布的,因此我假设,就 Auth0 而言,一切都很好。

所以,我相信,我在 .NET Core 项目上犯了一个错误。

标签: asp.net-coreauthorizationauth0

解决方案


好的,所以我找到了答案。实际上,最终取决于令牌,以及即将发生的事情。

虽然,我需要的瞄准镜来了,

  "permissions": [
    "read:penquotes"
  ]

.NET Core 没有查看必要范围的权限。它在看这里。

"scope": "openid profile email",

并且由于那里不存在必要的范围,因此授权被拒绝。最终,我更新了我的 React 客户端应用程序以请求必要的范围。

现在,看看正确的令牌,

{
  //other token things
  "scope": "openid profile email read:penquotes"
}

现在,授权继续进行,没有任何问题。看起来我的 .NET Core 配置很好,但是在请求令牌时我犯了一个错误。


推荐阅读