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

IdentityServer4部署Azure容器仓库后签名密钥未找到的认证问题

这个问题我之前也碰到过!根源就在于你用了AddDeveloperSigningCredential()这个方法——它是给开发环境用的临时方案,每次IdentityServer容器重启或者重新部署时,都会生成新的临时签名密钥,导致API验证旧token时找不到对应的签名密钥,就抛出了The signature key was not found错误。

接下来给你两种靠谱的解决方案,选一种适合你部署场景的就行:

方案一:使用文件存储的RSA密钥

  1. 先生成一对RSA密钥文件,可以用OpenSSL命令:
# 生成私钥
openssl genrsa -out private.key 2048
# 生成公钥
openssl rsa -in private.key -pubout -out public.key
  1. 把这两个密钥文件放到IdentityServer项目的根目录,右键文件设置「复制到输出目录」为「如果较新则复制」,确保打包镜像时能包含这些文件。
  2. 修改IdentityServer的服务配置,替换掉AddDeveloperSigningCredential():
// 注入IWebHostEnvironment获取项目根路径
private readonly IWebHostEnvironment _env;
public Startup(IWebHostEnvironment env)
{
    _env = env;
}

// 在ConfigureServices里修改
var privateKeyPath = Path.Combine(_env.ContentRootPath, "private.key");
var privateKey = new RsaSecurityKey(File.ReadAllText(privateKeyPath));

services.AddIdentityServer()
    .AddSigningCredential(privateKey) // 替换成这行
    .AddAspNetIdentity<ApplicationUser>()
    .AddConfigurationStore(options => {
        options.ConfigureDbContext = builder => builder.UseNpgsql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
    })
    .AddOperationalStore(options => {
        options.ConfigureDbContext = builder => builder.UseNpgsql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
        options.EnableTokenCleanup = true;
        options.TokenCleanupInterval = 30;
    });

方案二:使用X.509证书(更适合生产环境)

如果是部署在Azure,推荐用Azure Key Vault托管证书;如果是自建环境,可以用自签名证书:

  1. 生成自签名证书(或者从CA获取):
# 生成pfx格式的自签名证书,有效期10年
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650
openssl pkcs12 -export -out mycert.pfx -inkey key.pem -in cert.pem
  1. 把pfx文件放到IdentityServer项目里,同样设置复制到输出目录。
  2. 修改配置代码:
var certPath = Path.Combine(_env.ContentRootPath, "mycert.pfx");
// 替换成你的证书密码
var cert = new X509Certificate2(certPath, "your-cert-password");

services.AddIdentityServer()
    .AddSigningCredential(cert) // 使用证书签名
    // 其他配置不变...

额外注意事项

  • 生产环境一定要把options.RequireHttpsMetadata = true,避免明文传输元数据。
  • 确保部署时密钥/证书文件能被容器正确访问,如果是用Docker,可以把文件打包进镜像,或者用卷挂载的方式管理(更安全,避免密钥泄露到镜像里)。
  • API服务的AuthorityUrl必须正确指向IdentityServer的公网地址,不能用localhost或者内部测试地址(除非是同一Docker网络内的服务名)。

这样修改后,不管IdentityServer怎么重启或者重新部署,签名密钥都是固定的,API就能正常验证token了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:44