【发布时间】:2020-12-15 18:21:17
【问题描述】:
我在 ASP.NET Core 3.1 项目中有以下 Identity Server 4 配置:
services
.AddIdentityServer(y => {
y.Events.RaiseErrorEvents = true;
y.Events.RaiseInformationEvents = true;
y.Events.RaiseFailureEvents = true;
y.Events.RaiseSuccessEvents = true;
})
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.IdentityResources())
.AddInMemoryApiResources(Config.ApiResources())
.AddInMemoryApiScopes(Config.GetApiScopes())
.AddInMemoryClients(Config.Clients)
.AddProfileService<ProfileService>()
.AddAspNetIdentity<User>();
Config 如下:
public static class Config {
public static List<ApiResource> ApiResources() {
return new List<ApiResource> {
new ApiResource("api", "API Resource")
};
}
public static List<ApiScope> ApiScopes() {
return new List<ApiScope> {
new ApiScope("api", "API Scope")
};
}
public static List<IdentityResource> IdentityResources() {
return new List<IdentityResource> {
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email()
};
}
public static List<Client> Clients() {
return new List<Client> {
new Client {
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets = { new Secret("Secret".Sha256()) }
AllowedScopes = {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
IdentityServerConstants.StandardScopes.OfflineAccess,
"api"
}
}
};
}
}
在我拥有的 API 上:
services
.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, x => {
x.ApiName = "api";
x.ApiSecret = "Secret"
x.Authority = Config.AuthorityUrl;
x.RequireHttpsMetadata = true;
x.EnableCaching = true;
x.CacheDuration = TimeSpan.FromMinutes(20);
});
我使用 Insomnia 客户端和 OAuth2 调用了一个 API 端点:
我能够获取访问令牌,但在调用 API 时出现错误:
Bearer error="invalid_token", error_description="The audience 'empty' is invalid"
我使用 JWT 检查了访问令牌,得到以下信息:
标题
{
"alg": "HS256",
"kid": "A1042705E52832C676596F36BB1898AB",
"typ": "at+jwt"
}
有效载荷
{
"nbf": 1598478410,
"exp": 1598482010,
"iss": "https://localhost:5000",
"client_id": "mvc",
"jti": "23525FF997FD4D71E13C786A7AD07B5D",
"iat": 1598478410,
"scope": [
"api"
]
}
aud 丢失。但是我需要吗?阅读 IS4 文档后,我尝试添加:
.AddIdentityServer(y => {
y.EmitStaticAudienceClaim = true;
现在访问令牌有aud 字段,但它的值不是api。不应该吗?
"aud": "https://localhost:5000/resources"
现在调用 API 时出现错误:
Bearer error="invalid_token", error_description="The audience 'https://localhost:5000/resources' is invalid"
我阅读了文档和 IS4 示例,但找不到解决方案。
我错过了什么?
【问题讨论】:
标签: asp.net-core jwt identityserver4 asp.net-core-3.1