【问题标题】:How to create RsaSecurityKey.KeyId with IdentityServer4如何使用 IdentityServer4 创建 RsaSecurityKey.KeyId
【发布时间】:2022-01-19 10:14:36
【问题描述】:

我正在使用 IdentiyServer4 生成令牌,我正在使用 AddDeveloperSigningCredential() 方法生成带有 KeyId 的 RSA 密钥。

但是,在生产中,我使用AddSigningCredential(CreateSigningCredential()) 来生成这样的密钥:

private SigningCredentials CreateSigningCredential()
        {
            var signinkey = new RsaSecurityKey(RSA.Create());
            signinkey.KeyId = "abcdefghijklmnopqrstuvwxyz";//How to generate KeyId ??
            var credentials = new SigningCredentials(signinkey,
                SecurityAlgorithms.RsaSha256);

            return credentials;
        }

如何生成 KeyId?我可以将其设置为任意值吗?

【问题讨论】:

    标签: asp.net-core jwt rsa openid-connect


    【解决方案1】:

    您不需要设置 keyId 并在代码中自己创建 RSA 密钥,这听起来像是不好的做法。然后你也可以使用 AddDeveloperSigningCredential 方法。

    您实际上可以在此处查看该方法的源代码,以了解它们如何在代码中执行此操作: https://github.com/DuendeSoftware/IdentityServer/blob/main/src/IdentityServer/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs

    但是,在生产中,您应该在外部生成密钥并将其传递给 IdentityServer,因此密钥在重新部署/重新启动时是相同的。否则之前发行的令牌将不再有效。

    例如,您可以将密钥存储在 Azure Key Vault 中,或使用其他一些配置/秘密系统。或者在数据库中或作为某个文件。

    如果你想手动创建一个,使用 OpenSSL,那么你可以写

    openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -aes256 -out rsa-private-key.pem
    

    【讨论】:

    • 非常感谢,我使用 openssl 生成我的密钥,它工作正常。
    • 太棒了!很高兴我的回答有帮助!
    猜你喜欢
    • 2018-05-12
    • 2018-10-05
    • 1970-01-01
    • 2020-01-27
    • 2021-10-27
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多