使用IdentityServer4时,如何修改令牌验证参数,以使令牌发行者不被验证或可以提供多个有效发行者?
我尝试了以下方法,但这似乎不起作用:
public void ConfigureServices(IServiceCollection services)
{
// ... omitted
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ApiName = scopeName;
});
services.PostConfigure<JwtBearerOptions>("Bearer", options =>
{
// Option 1: turn off issuer validation at all
options.TokenValidationParameters.ValidateIssuer = false;
// Option 2 (preferable): Provide multiple valid issuers
options.TokenValidationParameters.ValidIssuers = new[]
{
"http://localhost:5000",
"http://127.0.0.1:5000",
};
});
// ... omitted
}
我之所以需要这样做的原因:受身份服务器保护的API可以在内部和外部访问。外部方与内部方使用不同的URL从身份服务器获取令牌,因此受保护的API应该同时将内部和外部URL视为有效。
答案 0 :(得分:1)
好的,在检查了GitHub存储库IdentityServer4.AccessTokenValidation之后,我找到了一种方法来实现。我的测试确认它可以正常工作。
public void ConfigureServices(IServiceCollection services)
{
// ... omitted
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(
IdentityServerAuthenticationDefaults.AuthenticationScheme,
jwtOptions =>
{
jwtOptions.Authority = "http://localhost:5000";
jwtOptions.RequireHttpsMetadata = false;
// This previously was: options.ApiName = scopeName;
jwtOptions.Audience = scopeName;
// Option 1: if you want to turn off issuer validation
//jwtOptions.TokenValidationParameters.ValidateIssuer = false;
// Option 2: if you want to support multiple issuers
jwtOptions.TokenValidationParameters.ValidIssuers = new[]
{
"http://localhost:5000",
"http://127.0.0.1:5000",
};
},
null
);
// ... omitted
}