我们有一个应用程序使用 IdentityServer4 cookie 授权方案进行用户登录,如下所示:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = <local IDP server with IdentityServer4>;
options.ClientId = <ClientId>;
options.ClientSecret = <secret>
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
})
IDP 上的客户端如下所示:new Client
{
ClientId = <ClientID>,
ClientName = <ClientName>,
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
RequireConsent = true,
ClientSecrets = { new Secret(<secret>.Sha256()) },
AllowOfflineAccess = true,
RedirectUris = { "http://" + ip + "/signin-oidc" },
PostLogoutRedirectUris = { "http://" + ip + "/signout-callback-oidc" },
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile
}
};
我们还有一个位于/api/...目标是向 API 添加 JWT Bearer Token 授权。为此,我添加了以下代码:
.AddJwtBearer(jwtOptions =>
{
jwtOptions.Authority = <local IDP server with IdentityServer4>;
jwtOptions.Audience = <ClientID>
jwtOptions.SaveToken = true;
})
API受到保护[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
登录后,我得到了 token await HttpContext.GetTokenAsync("access_token");
但是,当我尝试使用该 token 访问 API 时,出现以下错误:AuthenticationFailed: IDX10214: Audience validation failed. Audiences: 'http://localhost:50059/resources'. Did not match: validationParameters.ValidAudience: ClientID or validationParameters.ValidAudiences: 'null'.
事实上,当我使用 jwt.io 解码 token 时,
aud
设置为 http://localhost:50059/resources
,而 ClientID 显示为新字段 'client_id': '<ClientID>'
.到目前为止我发现的表明
aud
始终设置为 <idp>/resources
访问 token ,并且该 API 访问是通过 token 内的范围声明来处理的。但是,我不明白如何正确设置。有谁知道问题出在哪里以及我如何解决它?
最佳答案
事实证明,解决方案非常简单。正如怀疑的那样,它与范围有关。我早些时候试图解决这个问题,但它一直说“无效范围”......因为我从未创建过 API 资源,呃。
new ApiResource("api-name", "API Name")
client.AllowedScopes.Add("api-name")
options.Scopes.Add("api-name")
options.Audience = "api-name"
或者options.ApiName = "api-name"
有了这个,我现在可以使用访问 token 来访问我的 API。
关于asp.net-core - 为登录设置 IdentityServer4 Cookies 的正确方法,用于 API 授权的 JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50264059/