我已经使用 Azure AD 为我的 ASP.NET Core 3.0 Web API 实现了身份验证。当我使用 [Authorize]
属性时,我收到带有消息的 http 401 错误响应
Bearer error="invalid_token", error_description="未找到签名密钥"
我目前在 ConfigureService()
中的 Startup.cs
看起来像这样:
options.AddSecurityDefinition("oauth", new OpenApiSecurityScheme()
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
TokenUrl = new Uri($"https://login.microsoftonline.com/<mytenantid>/oauth2/v2.0/token"),
AuthorizationUrl = new Uri($"https://login.microsoftonline.com/TenantId/oauth2/v2.0/authorize", UriKind.RelativeOrAbsolute),
Scopes = { { "api://<myappid>/user_impersonation", "user_impersonation" } }
}
}
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = $"https://login.microsoftonline.com/<mytenantid>/v2.0";
o.Audience = "<myappid>";
o.TokenValidationParameters.ValidAudiences = new string[] { "<myappid>", $"api://<myappid>" };
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "oauth"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
如果我遗漏了什么,请告诉我
答案 0 :(得分:0)
我之前回答过很多类似的问题。根据您的问题,您公开了受 Azure 保护的 web api。接下来,您需要创建一个客户端应用程序,并使用该客户端应用程序调用 api 应用程序。
通常 401 错误意味着您的令牌的受众与您的 api 不匹配。使用token调用api时,会收到401未授权错误。访问令牌是根据受众发布的,因此您必须确保在请求令牌时将 scope
设置为您的 api。当然你也可以解析token,检查aud
声明,确定是你要调用的api。
我用auth code flow为你做一个简单的演示:
接下来,在“API 权限”下,授予您的前端应用程序访问后端 API 应用程序的权限:
解析token: