IdentityServer4:服务到服务呼叫无法找到受众

时间:2017-08-03 12:13:41

标签: asp.net-core openid-connect identityserver4

我正在尝试使用IdentityServer4来验证Micoservices体系结构的用户。当我尝试从我的Web App控制器调用另一个Web API服务时,调用在Web API服务上失败,控制台上的消息如下所示:

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: 
IDX10214: Audience validation failed. 
Audiences: 'null/resources'. Did not match: validationParameters.ValidAudience: 'hierarchy' or validationParameters.ValidAudiences: 'null'.

我的电话链如下:

[User] --> [ASP.Net core MVC: Web App ]--> [ASP.Net core MVC: Web Api ]

我使用Identity server使用以下配置创建了IdentityServer4

API资源

new ApiResource("hierarchy", "Hierarchy Configuration API"),
new ApiResource("deviceconfiguration", "Device Configuration API"),

客户

new Client
{
   ClientId = "system.health.check",
   ClientName = "System health check client",
   AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

   ClientSecrets = { new Secret("secret".Sha256()) },
   AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "healthcheck"
                    },

    RedirectUris = { "http://localhost:5100/signin-oidc",  "http://localhost:5103/signin-oidc",},
    PostLogoutRedirectUris = { "http://localhost:5100/signout-callback-oidc" },
}

服务 - 启动

services.AddIdentityServer(x => x.IssuerUri = "null")
        .AddSigningCredential(Certificate.Certificate.Get())
        .AddTemporarySigningCredential()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApiResources())
        .AddInMemoryClients(Config.GetClients())
        .AddTestUsers(Config.GetUsers());

[ASP.Net核心MVC:Web App]

我已按照以下方式设置我的运作:

"OpenIdConnectOptions": {
  "AuthenticationScheme": "oidc",
  "SignInScheme": "Cookies",
  "Authority": "http://localhost:5000",
  "RequireHttpsMetadata": false,
  "ClientId": "system.health.check",
  "ClientSecret": "secret",
  "ResponseType": "code id_token",
  "GetClaimsFromUserInfoEndpoint": true,
  "SaveTokens": true
}

启动时的配置代码如下所示:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationScheme = "Cookies"
});

var option1 = new OpenIdConnectOptions();
Configuration.GetSection("Security:OpenIdConnectOptions").Bind(option1);
app.UseOpenIdConnectAuthentication(option1);

到目前为止这种方法效果很好,我可以看到,当用户未经过身份验证时,他将被定向到身份服务器并且令牌出现问题。

现在的问题是,我希望将此服务的呼叫表格路由到另一个Web API service,该另一个hierarchy也受到var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token"); var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5103/api/Hierarchy/22"); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var _client = new HttpClient(); var response = await _client.SendAsync(requestMessage); return await response.Content.ReadAsStringAsync(); 范围的保护,如下所示:

服务电话

"IdentityServerAuthenticationOptions": {
  "Authority": "http://localhost:5000",
  "RequireHttpsMetadata": false,
  "ApiName": "hierarchy",
  "AllowedScopes": [
    "openid",
    "hierarchy"
  ]

[ASP.Net核心MVC:Web Api]

启动设置与我的其他服务相同,但由于这是资源服务,因此我的配置不同:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
     AuthenticationScheme = "Cookies"
});

var option2 = new IdentityServerAuthenticationOptions();
Configuration.GetSection("Security:IdentityServerAuthenticationOptions").Bind(option2);
app.UseIdentityServerAuthentication(option2);

启动时的配置代码如下所示:

Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10214: Audience validation failed. Audiences: 'null/resources'. Did not match: validationParameters.ValidAudience: 'hierarchy' or validationParameters.ValidAudiences: 'null'.
   at Microsoft.IdentityModel.Tokens.Validators.ValidateAudience(IEnumerable`1 audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwt, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext() 

现在问题是调用没有返回任何内容,在这个服务的控制台上我看到一个日志说:

[Web App]

当我解码{ "nbf": 1501764330, "exp": 1501767930, "iss": "null", "aud": "null/resources", "client_id": "system.health.check", "sub": "2", "auth_time": 1501764327, "idp": "local", "scope": [ "openid", "profile" ], "amr": [ "pwd" ] } 上的访问令牌时,这就是我所看到的

Audience

所以它明显缺少healthcheck以及范围Audience 关于为什么它错过了focus : Id -> Task Error () focus = Native.Dom.focus 或我在这里缺少什么的任何想法?

1 个答案:

答案 0 :(得分:1)

假设您的api名称是“层次结构”,请尝试在客户端配置中的允许范围中传递它。这里:

new Client
{
   ClientId = "system.health.check",
   ClientName = "System health check client",
   AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,

   ClientSecrets = { new Secret("secret".Sha256()) },
   AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "healthcheck" <------
                    },

    RedirectUris = { "http://localhost:5100/signin-oidc",  "http://localhost:5103/signin-oidc",},
    PostLogoutRedirectUris = { "http://localhost:5100/signout-callback-oidc" },
}

您可以在运行状况检查

之后添加它