You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core3.1+IdentityServer4限制JWKS暴露遇授权错误求助

解决方案

核心问题在于:开启options.Discovery.ShowKeySet = false后,API服务无法从IdentityServer的发现文档获取JWKS密钥,导致无法验证JWT令牌,进而触发未授权错误。由于你使用对称密钥签名令牌(未使用证书),可以通过以下两步彻底解决:

1. 隐藏JWKS端点并配置IdentityServer固定签名密钥

修改IdentityServer的启动配置,开启JWKS隐藏,同时显式指定用于签名JWT的对称密钥:

services.AddIdentityServer(options =>
{
    options.Discovery.ShowIdentityScopes = false;
    options.Discovery.ShowApiScopes = false;
    options.Discovery.ShowClaims = false;
    options.Discovery.ShowExtensionGrantTypes = false;
    options.Discovery.ShowEndpoints = false;
    options.Discovery.ShowTokenEndpointAuthenticationMethods = false;
    options.Discovery.ShowKeySet = false; // 正式隐藏JWKS端点
})
.AddInMemoryClients(IdentityServerConfig.Clients)
.AddInMemoryApiScopes(IdentityServerConfig.ApiScopes)
// 添加对称签名密钥,需与Client配置中的原始明文密钥一致
.AddSigningCredential(new SymmetricSecurityKey(Encoding.UTF8.GetBytes("你的客户端明文密钥")));

注意:这里必须使用Client配置中ClientSecrets的原始明文密钥,而非Sha256哈希后的字符串。

2. 修改API认证配置,直接指定验证密钥

API不再依赖IdentityServer的JWKS端点,改用直接配置对称密钥的方式验证令牌,替换原有的AddIdentityServerAuthentication:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = applicationUrl, // IdentityServer的地址
            ValidateAudience = true,
            ValidAudience = IdentityServerConfig.ApiName,
            ValidateIssuerSigningKey = true,
            // 使用与IdentityServer完全一致的对称密钥
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("你的客户端明文密钥")),
            ValidateLifetime = true
        };
    });

额外注意事项

  • 你的Client Credentials授权模式完全适配对称密钥签名,无需依赖JWKS或证书。
  • 生产环境中不要硬编码密钥,建议从appsettings.json或专业密钥管理服务中读取,保障密钥安全。

内容的提问来源于stack exchange,提问作者Rosario

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:05:25