我有一个类似于此示例的 ASP.NET Core 3.1 项目:在 WPF 桌面应用程序中使用 Microsoft 身份平台登录用户并调用 ASP.NET Core Web API。
我使用的是Identity web
1.0 版和 Azure AD,单租户应用程序。
我编辑了清单添加appRoles
,因为我只请求应用程序令牌,而不是用户令牌:
[... more json ...]
"appId": "<guid>",
"appRoles": [
{
"allowedMemberTypes": [
"Application"
],
"description": "Accesses the application.",
"displayName": "access_as_application",
"id": "<unique guid>",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "access_as_application"
}
],
"oauth2AllowUrlPathMatching": false,
[... more json ...]
我还启用了idtyp
访问令牌声明,以指定这是一个应用程序令牌。:
[... more json ...]
"optionalClaims": {
"idToken": [],
"accessToken": [
{
"name": "idtyp",
"source": null,
"essential": false,
"additionalProperties": []
}
],
"saml2Token": []
[... more json ...]
以下请求是通过 Postman 提出的。请注意与范围有关的使用,它在与客户端凭据授予流程/.default
相关的文档中提到。
POST /{tenant_id}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
scope=api%3A%2F%2{client_id}%2F.default
&client_id={client_id}
&grant_type=client_credentials
&client_secret={secret_key}
该请求返回一个access_token
可以使用jwt.ms查看的内容,如下所示,出于安全原因,实际数据已被占位符替换。:
{
"typ": "JWT",
"alg": "RS256",
"x5t": "[...]",
"kid": "[...]"
}.{
"aud": "api://<client_id>",
"iss": "https://sts.windows.net/<tenant_id>/",
"iat": 1601803439,
"nbf": 1601803439,
"exp": 1601807339,
"aio": "[...]==",
"appid": "<app id>",
"appidacr": "1",
"idp": "https://sts.windows.net/<tenant_id>/",
"idtyp": "app",
"oid": "<guid>",
"rh": "[..].",
"roles": [
"access_as_application"
],
"sub": "<guid>",
"tid": "<guid>",
"uti": "[...]",
"ver": "1.0"
}
我注意到上面的令牌不包括scp
. 这似乎是正确的,因为这是应用程序令牌而不是用户令牌。相反,它包含“角色”,作为应用程序令牌的适用。
现在access_token
可以在 Postman Get 中用作承载:
GET /api/myapi
Host: https://localhost:5001
Authorization: Bearer {access_token}
对此请求的响应是500 internal error
。即有什么问题。看起来像一个正确的access_token
应用程序令牌,所以错误似乎在 ASP.NET Core 3.1 控制器端。
ASP.NET 核心 3.1。托管自定义 API 的项目,startup.cs
其中包含以下代码:
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
// This is added for the sole purpose to highlight the origin of the exception.
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
var existingOnTokenValidatedHandler = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = async context =>
{
if (context.Principal.Claims.All(x => x.Type != ClaimConstants.Scope)
&& context.Principal.Claims.All(y => y.Type != ClaimConstants.Scp)
&& context.Principal.Claims.All(y => y.Type != ClaimConstants.Roles))
{
// This where the exception originates from:
throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
}
};
});
该appsettings.json
项目包括:
"AzureAD": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mydomain.onmicrosoft.com",
"ClientId": "<client_id>",
"TenantId": "<tenant_id>",
"Audience": "api://<client_id>"
},
...控制器看起来像这样:
[Authorize]
[Route("api/[controller]")]
public class MyApiController : Controller
{
[HttpGet]
public async Task<string> Get()
{
return "Hello world!";
}
}
的根本原因500 internal error
是抛出了这个异常:IDW10201: Neither scope or roles claim was found in the bearer token.
异常。
更新:
(有关更多详细信息,请参阅下面的答案)。
这段关于“使用 Microsoft 标识平台在您的应用程序中实现授权 - 2020 年 6 月”的视频表明缺少的部分是JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
需要设置的这个标志startup.cs
- 例如:
public void ConfigureServices(IServiceCollection services)
{
// By default, the claims mapping will map clain names in the old format to accommodate older SAML applications.
//'http://schemas.microsodt.com/ws/2008/06/identity/clains/role' instead of 'roles'
// This flag ensures that the ClaimsIdentity claims collection will be build from the claims in the token
JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
[...more code...]