我正在尝试在 .NET 7 WebApi 项目中为 AWS Cognito 设置访问令牌验证。问题是 AWS 会轮换其密钥,因此您需要经常获取新密钥。我发现的大多数解决方案每次使用如下代码调用验证器时都会调用端点:
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
// get JsonWebKeySet from AWS
var json = new WebClient().DownloadString(jwtKeySetUrl);
// serialize the result
var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
// cast the result to be the type expected by IssuerSigningKeyResolver
return (IEnumerable<SecurityKey>)keys;
},
问题是,至少在 .NET 7 中,WebClient 已被弃用,您应该改用 HttpClient。这就是我想出的:
IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
{
// get JsonWebKeySet from AWS
var json = new HttpClient()
.GetStringAsync($"{builder.Configuration["AWS:Issuer"]}/.well-known/jwks.json")
.ConfigureAwait(false).GetAwaiter().GetResult();
// serialize the result
var keySet = JsonWebKeySet.Create(json); // Ignore this, just cleaned up the Json deserialization code from the above example since JsonWebKeySet can do it directly.
var keys = keySet.Keys;
// cast the result to be the type expected by IssuerSigningKeyResolver
return keys;
},
我关心的是为每个调用创建 HttpClient,因为我知道这可能效率低下,并且我想确保此代码是可扩展的。将代码包装在“using HttpClient”中会更好还是上面的可以?我确信每次都调用第三方端点并不是很好,但我认为我对此无能为力。
默认情况下,JwtBearer 将每 24 小时刷新一次配置和密钥。
您可以使用
来控制它.AddJwtBearer(opt =>
{
opt.AutomaticRefreshInterval = new TimeSpan(1, 0, 0, 0);
opt.BackchannelTimeout = new TimeSpan(0, 0, 10); //10 seconds
}
这对你不起作用吗?