因此,我尝试使用 Azure AD B2C 保护 Web API,但是当我尝试使用使用“运行用户流”获取的令牌访问端点时,出现以下异常:
<块引用>System.UnauthorizedAccessException: IDW10201: 既不是作用域也不是角色 在不记名令牌中发现了声明。
我的代码:
我创建了一个新的 ASP.NET Core 应用程序并使用对话框自动添加身份验证。
代码中的一些有趣点:
我尝试将以下内容添加到 appsettings.json 文件中,但没有帮助:
"AllowWebApiToBeAuthorizedByACL": true
我尝试从控制器中删除它,但没有帮助:
// The Web API will only accept tokens 1) for users, and 2) having the "access_as_user" scope for this API
static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };
HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
在 ConfigureServices 中,我有以下代码:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));
Azure 门户:
我为 Azure AD B2C 创建了一个新租户
我注册了一个应用程序
在这里我玩了很多,这些是我现在启用的权限:
然后,当我运行用户流程时,这就是我得到的:
使用的链接:
<块引用>https://xxxxxxxxxxx001.b2clogin.com/xxxxxxxxx001.onmicrosoft.com/oauth2/v2.0/authorize?
p=B2C_1_user_flow_test_signinsignup
&client_id=xxxxxxxxxxxx
&nonce=defaultNonce
&redirect_uri=https%3A%2F%2Fjwt.ms
&scope=openid
&response_type=id_token
&prompt=登录
我对 azure 完全陌生,在研究了整个互联网后,我无法弄清楚这里的问题是什么,以及为什么 scp 不在我从 azure 门户中提供的链接运行用户流时获得的令牌中。
如果能帮助我解决我缺少的设置或设置错误的问题,我将不胜感激。
答案 0 :(得分:4)
您得到的是 id 令牌。 id 令牌没有 scp
声明。它只包含登录用户的信息。您正在执行的只是登录用户的操作。
如果您想获得 scp
声明,您应该使用 request an access token 而不是 id 令牌。
答案 1 :(得分:1)
添加到 Carl 的回答中,使用 B2C 链接,您只会获得 ID 令牌,因为它将响应类型设置为 id_token,就像文章中所述。为了获得访问令牌,您的 response_type 字段需要是 'response_type=code' 或 'response_type=code+id_token',即使这样 JWT.ms 也不会显示它。如果您捕获开发工具网络跟踪,您将在 authresp 框架 access_token 和 id_token 中看到两个参数。使用 jwt.io 解码 access_token 将向我们展示您正在寻找的内容。