简体   繁体   English

asp.net 核心 AzureADJwtBearer 颁发者验证失败

[英]asp.net core AzureADJwtBearer issuer validation failure

I have the stock file |我有库存文件 | new |新 | web |网| asp.net core web api project template where I selected AzureAD authentication that generated the following Startup.cs asp.net core web api 项目模板,我选择了 AzureAD 身份验证,生成了以下 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

and the following appsettings.json和以下 appsettings.json

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mymsdn.onmicrosoft.com",
    "TenantId": "<my azuread tenant id>",
    "ClientId": "<my azuread web app id>"
  }

I'm using postman to acquire token leveraging a public client profile app setup just as I have done for another web api setup that is working as expected with the same azureAd bearer token auth code and settings coordinates.我正在使用邮递员来利用公共客户端配置文件应用程序设置获取令牌,就像我为另一个 web api 设置所做的那样,该设置按预期使用相同的 azureAd 承载令牌身份验证代码和设置坐标。

For some reason this app is trying to validate the wrong token issuer format and i'm at a loss as to how I correct it.出于某种原因,这个应用程序试图验证错误的令牌发行者格式,我不知道如何纠正它。

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AzureADJwtBearer was not authenticated. Failure message: IDX10205: Issuer validation failed. Issuer: 'https://login.microsoftonline.com/<my azuread tenantid>/v2.0'. Did not match: validationParameters.ValidIssuer: 'null' or validationParameters.ValidIssuers: 'https://sts.windows.net/<my azuread tenantid>/'.

Turns out this issue surfaces if you configured azuread app registrations entry for your ClientId to support any organization or consumer, aka microsoft account, signins instead of just your organization or any organization.如果您为 ClientId 配置了 azuread 应用程序注册条目以支持任何组织或消费者(又名 microsoft 帐户)登录,而不仅仅是您的组织或任何组织,则会出现此问题。 The fix was to use the AddJwtBearer() block of Startup.ConfigureServices() code shown below instead of the project template provided AddAzureADBearer() block.修复方法是使用下面显示的Startup.ConfigureServices()代码的AddJwtBearer()块,而不是项目模板提供的AddAzureADBearer()块。

public void ConfigureServices(IServiceCollection services)
{
    // if azuread app registrations entry for ClientId has "signInAudience": "AzureADMyOrg" or "AzureADMultipleOrgs" where "iss": "https://sts.windows.net/{TenantId}/"
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => //Configuration.Bind("AzureAd", options));
        {
            Configuration.Bind("AzureAd", options);
            Log.LogInformation($"the AddAzureADBearer options have been configured for ClientId = {options.ClientId}");
        });

    // if azuread app registrations entry for ClientId has "signInAudience": "AzureADandPersonalMicrosoftAccount" where "iss": "https://login.microsoftonline.com/{TenantId}/v2.0"
    services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
        .AddJwtBearer(options =>
        {
            var azureadoptions = new AzureADOptions(); Configuration.Bind("AzureAd", azureadoptions);
            options.Authority = $"{azureadoptions.Instance}{azureadoptions.TenantId}/v2";
            options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                ValidAudience = $"{azureadoptions.ClientId}",
                //ValidAudiences = new List<string> { $"{azureadoptions.ClientId}", $"api://{azureadoptions.ClientId}", $"https://myapp.azurewebsites.net/" },
                //ValidIssuer = $"https://sts.windows.net/{azureadoptions.TenantId}/" // for "signInAudience": "AzureADMyOrg" or "AzureADMultipleOrgs"
                ValidIssuer = $"{azureadoptions.Instance}{azureadoptions.TenantId}/v2.0" // for "signInAudience": "AzureADandPersonalMicrosoftAccount"
                //ValidIssuers = new List<string> { $"https://sts.windows.net/{azureadoptions.TenantId}/", $"{azureadoptions.Instance}{azureadoptions.TenantId}/v2.0" }                        
            };

            Log.LogInformation($"the AddJwtBearer options have been configured for ClientId = {azureadoptions.ClientId}");
        });
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

I was trying to authenticate existing token from uwp-app in web-api and I had a similar issue:我试图在 web-api 中对来自 uwp-app 的现有令牌进行身份验证,但我遇到了类似的问题:

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: Failed to validate the token. Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:无法验证令牌。

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException: IDX10205: Issuer validation failed. Microsoft.IdentityModel.Tokens.SecurityTokenInvalidIssuerException:IDX10205:颁发者验证失败。 Issuer: ' https://spolujizda.b2clogin.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '.发行人:“ https://spolujizda.b2clogin.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ ”。 Did not match: validationParameters.ValidIssuer: 'null' or validationParameters.ValidIssuers: ' https://login.microsoftonline.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '.不匹配:validationParameters.ValidIssuer:'null'或validationParameters.ValidIssuers:' https : //login.microsoftonline.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '。

at Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)在 Microsoft.IdentityModel.Tokens.Validators.ValidateIssuer(String issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateIssuer(String issuer, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)在 System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateIssuer(String issuer, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)在 System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)在 System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken&validatedToken)
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()在 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AzureADB2CJwtBearer was not authenticated. Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:信息:AzureADB2CJwtBearer 未通过身份验证。 Failure message: IDX10205: Issuer validation failed.失败消息:IDX10205:颁发者验证失败。 Issuer: ' https://spolujizda.b2clogin.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '.发行人:“ https://spolujizda.b2clogin.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ ”。 Did not match: validationParameters.ValidIssuer: 'null' or validationParameters.ValidIssuers: ' https://login.microsoftonline.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '.不匹配:validationParameters.ValidIssuer:'null'或validationParameters.ValidIssuers:' https : //login.microsoftonline.com/4e8094c9-5058-454c-b201-ef61d7ae6619/v2.0/ '。 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Get", controller = "Values"}. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route 与 {action = "Get", controller = "Values"} 匹配。 Executing action Spolujizda.ApiServer.Controllers.ValuesController.Get (Spolujizda.ApiServer) Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.正在执行操作 Spolujizda.ApiServer.Controllers.ValuesController.Get (Spolujizda.ApiServer) Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'. Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:过滤器“Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”处的请求授权失败。 Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (). Microsoft.AspNetCore.Mvc.ChallengeResult:Information: 使用身份验证方案执行 ChallengeResult ()。 Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: AzureADB2CJwtBearer was challenged. Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: AzureADB2CJwtBearer 受到质疑。 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Spolujizda.ApiServer.Controllers.ValuesController.Get (Spolujizda.ApiServer) in 8.105ms Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 8950.4739ms 401 text/plain Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: 在 8.105ms 内执行操作 Spolujizda.ApiServer.Controllers.ValuesController.Get (Spolujizda.ApiServer) Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: 请求在 8950.40133333ms 内完成/清楚的

But for me the fix was much simpler.但对我来说,修复要简单得多。

For Web API I had AzureAdB2C.Instance set to https://spolujizda.b2clogin.com/tfp/ .对于 Web API,我将 AzureAdB2C.Instance 设置为https://spolujizda.b2clogin.com/tfp/

For an UWP app, I had been issuing token via https://login.microsoftonline.com/tfp/对于 UWP 应用,我一直通过https://login.microsoftonline.com/tfp/颁发令牌

That is why it resulted in this error.这就是它导致此错误的原因。 Because in the UWP app, the token was issued for login.microsoft ... and in the Web API, it was trying to verify issuer as spolujizda.b2clogin...因为在 UWP 应用程序中,令牌是为login.microsoft ... 颁发的,而在 Web API 中,它试图将颁发者验证为 spolujizda.b2clogin ...

First I tried to change address for issuing token for uwp-app, but that didn't work.首先,我尝试更改为 uwp-app 颁发令牌的地址,但这没有用。

So secondly I just changed web-api's AzureAdB2C.Instance config to login.microsoft.... and it now works.其次,我只是将 web-api 的 AzureAdB2C.Instance 配置更改为 login.microsoft.... 现在它可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM