温馨提示:本文翻译自stackoverflow.com,查看原文请点击:angular - Problem with authenticating Azure AD tokens at Web API
angular asp.net-core azure-active-directory jwt msal.js

angular - 在Web API上验证Azure AD令牌的问题

发布于 2020-03-27 12:08:02

我有2个Web应用程序。

  • 站点A既是前端(Angular)也是用.NET Core编写的Web API。
  • 站点B是用.NET核心编写的Web API。

两个站点中的Web API相同。身份验证是相同的。


测试1:当我要求站点A使用其自己的API来获取数据(在启用站点A的身份验证的情况下)时,它运行良好。

测试2:当我要求站点A使用站点B来获取数据(在站点B的身份验证已关闭的情况下)时,它的工作原理很好。

测试3:当我要求站点A使用站点B来获取数据(在站点B的身份验证处于打开状态)时,它失败,并显示未经授权的错误401。

这是我用来验证的代码...

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
    o.MetadataAddress = String.Format("https://login.microsoftonline.com/{0}/v2.0/.well-known/openid-configuration", Configuration["AzureAd:TenantId"]);
    o.Audience = Configuration["AzureAd:ClientId"];
});

所以...

I know the tokens are getting passed correctly (because of Test A).

I know the Site B API being called is accessible and correct (because of Test B).

Therefore, I assume, the issue is with the values being passed to Azure AD. I assume Azure doesn't think the tokens being obtained in Site A and validated in Site B (that have different URIs) are not "the same" and therefore not authorised.

What do I need to pass to Azure to get it to work?

Thanks

查看更多

查看更多

提问者
Beakie
被浏览
164
Dylan Morley 2019-07-03 23:55

There are 3 bits of validation that will happen against the token

1) It will validate that it was signed by the public keys of the open id provider (e.g. retrieved from here https://login.microsoftonline.com/common/discovery/keys)

2)它将验证令牌的发行人(iss声明)对于API是否有效

3)它将验证令牌的受众(aud声明)对于该API是否有效

(还有一些额外的生命周期验证,但是这3个在配置时很重要)

您发送给API的令牌可能没有通过发行者受众验证。使用类似http://jwt.ms/的JWT解码器来检查令牌并了解正在发送到API的声明。

您的令牌的音频声明是否与您在Configuration [“ AzureAd:ClientId”]中指定的受众群体匹配?

如果两个令牌都是同一发行者,并且您对“站点B”从“站点A”接受令牌感到高兴,那么您可以在此处修改令牌验证参数以接受多个选项,请查看此答案作为示例

https://stackoverflow.com/a/47072385/1538039

调查令牌中的声明,然后修改站点B的配置,以允许您希望与之通信的受众/发布者来相应地验证声明。