我有 3 个项目 1-Javascript SPA 2-Web API 项目,3-带有 EF Core 的 IdentityServer
我开始调试 API 和 Identity Server 并成功获取 jwt token ,但是,当我尝试从具有授权属性的 API 方法获取值时,出现错误:
WWW-Authenticate →Bearer error="invalid_token", error_description="The audience is invalid"
我在身份验证选项中找不到有关受众的任何属性。这是我在 API 项目中的配置
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
ApiSecret="secret",
Authority = "http://localhost:5000",
ApiName="fso.Api",
RequireHttpsMetadata = false,
});
我的 Config.cs 文件在 Identity
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource()
{
Name = "fso.Api",
DisplayName = "feasion API",
Scopes =
{
new Scope("api1"),
new Scope(StandardScopes.OfflineAccess)
},
UserClaims =
{
JwtClaimTypes.Subject,
JwtClaimTypes.EmailVerified,
JwtClaimTypes.Email,
JwtClaimTypes.Name,
JwtClaimTypes.FamilyName,
JwtClaimTypes.PhoneNumber,
JwtClaimTypes.PhoneNumberVerified,
JwtClaimTypes.PreferredUserName,
JwtClaimTypes.Profile,
JwtClaimTypes.Picture,
JwtClaimTypes.Locale,
JwtClaimTypes.IdentityProvider,
JwtClaimTypes.BirthDate,
JwtClaimTypes.AuthenticationTime
}
}
};
}
public static List<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Email(),
new IdentityResources.Profile(),
};
}
// client want to access resources (aka scopes)
public static IEnumerable<Client> GetClients()
{
return new List<Client>
{
new Client
{
ClientId = "fso.api",
AllowOfflineAccess=true,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
AllowedScopes =
{
StandardScopes.OfflineAccess,
"api1"
}
}
};
}
}
最佳答案
见 here这个声明是关于什么的:
The aud (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected....
因此,当 JWT 由 API 中的中间件验证时,您的 API 名称必须存在于 aud 声明中,才能使 JWT 有效。您可以使用 jwt.io顺便看看你的 token ,这有助于理解它。
为了让 IdentityServer 将您的 API 名称添加到 aud 声明中,您的客户端代码(它试图从 API 获取资源,因此需要访问 token )应该从您的 API 请求一个范围。例如像这样(来自 MVC 客户端):
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
Authority = Configuration["IdpAuthorityAddress"],
ClientId = "my_web_ui_id",
Scope = { "api1" },
//other properties removed...
});
关于jwt - 观众无效错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909140/