【问题标题】:Validating access_token when identityserver goes offline身份服务器脱机时验证 access_token
【发布时间】:2019-06-04 19:30:22
【问题描述】:

我已经设置了 IdentityServer4。据我了解,我需要保护的 webapi 从 IdentityServer4 获取公钥并使用此密钥来验证 JWT 的签名密钥。我似乎找不到任何描述请求公钥频率的文档。每次验证都要求吗?是否缓存在需要验证的web api上?

我可以为公钥应用某种缓存,还是自动发生这种情况?

对于 web api,我使用标准 .NET Core 身份来设置 Bearer 的验证:

        services.AddAuthentication("JWT")
                .AddJwtBearer("JWT", options =>
                {
                    options.Authority = "https://identityserver4.tld";
                    options.RequireHttpsMetadata = false;
                    options.Audience = "webapi";
                });

看来我可以使用其中的一些代码,来自这里:https://devblogs.microsoft.com/aspnet/jwt-validation-and-authorization-in-asp-net-core/:

var tokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    ValidateIssuer = true,
    ValidIssuer = "http://localhost:5000/",
    IssuerSigningKey = new X509SecurityKey(new X509Certificate2(certLocation)),
};

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    Audience = "http://localhost:5001/", 
    AutomaticAuthenticate = true,
    TokenValidationParameters = tokenValidationParameters
});

这将在本地给我公钥,但仍然:在不使用上述 tokenValidationParameters 时,多久获取一次公钥?

【问题讨论】:

    标签: asp.net-core-2.0 identityserver4 asp.net-core-identity


    【解决方案1】:

    ASP.Net Core 中的默认身份验证中间件将调用您的 options.Authority uri 上的发现端点,并将缓存身份提供者指定的公钥(以及其他配置信息)。缓存当前在第一次进行身份验证时发生。上次我检查时,内存缓存被用于存储身份提供者配置(例如公钥)。

    目前PostConfigure(...) function here 似乎发生了这种情况。

    显然,理论上,您可以根据source codeJwtBearerOptions 中提供以下接口的实现,从而插入您自己的身份提供者配置管理。

        /// <summary>
        /// Responsible for retrieving, caching, and refreshing the configuration from metadata.
        /// If not provided, then one will be created using the MetadataAddress and Backchannel properties.
        /// </summary>
        public IConfigurationManager<OpenIdConnectConfiguration> ConfigurationManager { get; set; }
    

    默认实现使用OpenIdConnectConfigurationRetriever,你可以找到源代码here

    【讨论】:

    • 啊。谢谢。我理论上可以使用 redis 分布式缓存,然后在启动 webapi 的新实例时动态分配发现端点?
    • 是的,我刚刚查找了源代码,但您似乎无法轻松为此插入自己的缓存机制。
    • 好的。也许我会默认自己提供公钥。你能给我一个参考来源的链接吗?
    • 我在答案中做了,理论上你应该能够做一些事情,因为ConfgurationManager&lt;OpenIdConnectConfiguration&gt; 必须将IOptionsMonitor&lt;JwtBearerOptions&gt; 添加到 DI 中,以便稍后使用身份验证处理程序。
    • 啊。没看到链接。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多