基于策略的Auth0身份验证-始终返回Forbidden 403



我正在使用Auth0在我的后端API服务器中获得一些身份验证和授权。Auth0使用角色+权限系统,这与此处描述的策略概念兼容-https://learn.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服务器上,我有以下内容。这是我的ConfigureServices。

// 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-样本项目

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

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

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

不过,我需要的瞄准镜来了,

"permissions": [
"read:penquotes"
]

.NET Core没有在必要作用域的权限下进行查找。它在看这里。

"scope": "openid profile email",

由于那里不存在必要的范围,授权被拒绝。最终,我更新了我的React客户端应用程序,要求提供必要的作用域。

现在,看看正确的令牌

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

现在,授权正在顺利进行。看起来我的.NET Core配置很好,但我在请求令牌时犯了一个错误。

最新更新