我有2个Web应用程序。
两个站点中的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
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的配置,以允许您希望与之通信的受众/发布者来相应地验证声明。
感谢您提供非常清晰的反馈。我将对此进行调查并报告。而且,JWT解码器将非常有用。
因此,我检查了站点A生成的JWT令牌,看起来iss和aud值是正确的(与站点B相同)。
是否可以获得有关身份验证失败原因的一些信息?事件日志只是说验证失败。不是最有用的调试见解。
如果我调试了两个API请求,则站点A填充了ClaimsIdentity,而站点B没有填充。看来,Azure令牌索偿值根本不是问题。嗯 我现在将接受您的回答(因为它回答了我的原始假设)。
如果令牌验证参数失败,您将没有ClaimsIdentity。看看OnAuthenticationFailed事件,您可以像stackoverflow.com/a/48890853/1538039那样进行连接。进行令牌验证之后(根据github.com/aspnet/Security/blob/…),传递给该方法的上下文应具有Exception详细信息。