我们在Windows上成功运行了基于IdentityServer4的STS,其中Signing Credential已安装到本地计算机上,其中个人>证书下为.pfx,受信任人员>证书下为.cer。然后我们可以通过其Common Name加载Signing Credential,如下所示:
services.AddIdentityServer()
.AddSigningCredential("CN=CERT_NAME")
...
我们现在想要在Docker容器中运行我们的STS实现,并且已经遇到以下异常:
Unhandled Exception: System.PlatformNotSupportedException: Unix LocalMachine X509Store is limited to the Root and CertificateAuthority stores.
at Internal.Cryptography.Pal.StorePal.FromSystemStore(String storeName, StoreLocation storeLocation, OpenFlags openFlags)
at System.Security.Cryptography.X509Certificates.X509Store.Open(OpenFlags flags)
at IdentityModel.X509CertificatesFinder.Find(Object findValue, Boolean validOnly)
at Microsoft.Extensions.DependencyInjection.IdentityServerBuilderExtensionsCrypto.AddSigningCredential(IIdentityServerBuilder builder, String name, StoreLocation location, NameType nameType)
基于上面的错误消息,以及我们在这里使用的AddSigningCredential方法的来源:https://github.com/IdentityServer/IdentityServer4/blob/ec17672d27f9bed42f9110d73755170ee9265116/src/IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs#L73,很明显我们的问题是IdentityServer4正在本地机器的个人(“我的”)商店中寻找证书,但是,根据错误消息,这样的存储在Unix环境中不可用。
因此,我很想知道是否存在一些最佳实践,用于在Docker容器中加载IdentityServer4的签名凭据,如果无法通过名称或指纹加载它。唯一的选择是将证书与我们的应用程序捆绑在一起,然后按文件名加载吗?
感谢您提供的任何帮助!
我正在开发Windows机器,我使用以下代码从商店获取证书
X509Certificate2 cert = null;
X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
certStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = certStore.Certificates.Find(
X509FindType.FindByThumbprint,
"thumbprint",
false);
if (certCollection.Count > 0)
{
cert = certCollection[0];
Log.Logger.Information($"Successfully loaded cert from registry: {cert.Thumbprint}");
}
if (cert == null) // Fallback
{
cert = new X509Certificate2(Path.Combine(_env.ContentRootPath, "certificate.pfx"), "password");
//Log.Logger.Information($"Falling back to cert from file. Successfully loaded: {cert.Thumbprint}");
}
else
{
certStore.Dispose();
}
当您使用Docker容器和IdentityServer时,您有两个选择:
COPY certificate.pfx .
)-v /path/to/certificate.pfx:/certificate.pfx
)无论您选择哪种选项,您唯一需要的是将以下配置代码添加到ConfigureServices
中的Startup
var identityServerBuilder = services.AddIdentityServer();
/* store configuration and etc. is omitted */
if (_hostingEnvironment.IsDevelopment())
{
identityServerBuilder.AddDeveloperSigningCredential();
}
else
{
var certificate = new X509Certificate2("certificate.pfx", "certificate_password");
identityServerBuilder.AddSigningCredential(certificate);
}
从配置,环境变量或秘密存储中读取证书密码也是一个好主意。