我正在尝试设置一个使用 Azure Key Vault 密钥来执行 JWT 签名的 OpenIddict 服务器(我不是尝试将 RSA 密钥存储在 AKV 密钥中然后使用它;我正在尝试使用凭据设置 OpenIddict使用 AKV Key,它可以请求 AKV 执行签名)。
下面是如何创建使用此类密钥的 JWT 的片段:
var token = new JwtSecurityToken(
_configuration.Issuer,
_configuration.Audience,
claims,
expires: expiration == null ? null : now.Add(expiration.Value),
new SigningCredentials(
new KeyVaultSecurityKey(
_configuration.RsaKeyUri,
async (authority, resource, scope) =>
{
var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(new TokenRequestContext(new[] { resource + "/.default" }));
return token.Token;
}
), "RS256")
{
CryptoProviderFactory = new CryptoProviderFactory() { CustomCryptoProvider = new KeyVaultCryptoProvider() }
}
);
从 OpenIddict 中可用的中间件来看,正确的方法似乎是使用
AddSigningCredentials
这是我迄今为止尝试使用的(释义):
services.AddOpenIddict()
.AddServer(options =>
{
options.AddSigningCredentials(new SigningCredentials(
new KeyVaultSecurityKey(
Configuration["JwtSigning:AkvKeyUri"],
async (authority, resource, scope) =>
{
var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(
new TokenRequestContext(new[] { resource + "/.default" }));
return token.Token;
}
), Configuration["JwtSigning:KeyType"]));
但是在启动时,它会抱怨必须至少配置一个非对称签名密钥。如果使用
AddSigningCredentials
不能实现这一点,我实际上应该如何做到这一点?
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: At least one asymmetric signing key must be registered in the OpenIddict server options.
Consider registering a certificate using 'services.AddOpenIddict().AddServer().AddSigningCertificate()' or 'services.AddOpenIddict().AddServer().AddDevelopmentSigningCertificate()' or call 'services.AddOpenIddict().AddServer().AddEphemeralSigningKey()' to use an ephemeral key.
at OpenIddict.Server.OpenIddictServerConfiguration.PostConfigure(String name, OpenIddictServerOptions options)
at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd[TArg](String name, Func`3 createOptions, TArg factoryArgument)
at OpenIddict.Server.OpenIddictServerFactory.CreateTransactionAsync()
at OpenIddict.Server.AspNetCore.OpenIddictServerAspNetCoreHandler.HandleRequestAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
我认为这是因为密钥没有成功获取。 你可以尝试更换
var credential = new DefaultAzureCredential();
到
var credential = new ClientSecretCredential("{tenantId}", "clientId", "{clientSecret}");
为了确保您拥有正确的凭证,请获取密钥。