当通过以下方式使用 AddOidcStateDataFormatterCache 方法时:
services.AddOidcStateDataFormatterCache();
它仅适用于使用
.AddOpenIdConnect();
有没有办法在使用时应用分布式缓存格式化程序
.AddGoogle()
Google也是一个OpenId提供程序,可以使用.AddOpenIdConnect 或 .添加谷歌,但使用 .AddGoogle 不使用状态数据格式化程序。我通过检查 redis 缓存(用作 IDistributedCache 的底层实现(来确认这一点,并看到创建了一个密钥"DistributedCacheStateDataFormatter..."使用 .AddOpenIdConnect,但在使用 时不会创建任何内容。添加谷歌。
我想这可能是因为.AddGoogle可能会使用不同的身份验证处理程序,该处理程序不会由AddOidcStateDataFormatterCache自动选取
这是因为GoogleOptions
类继承自OAuthOptions
而不是OpenIdConnectOptions
但它们都有一个ISecureDataFormat<AuthenticationProperties> StateDataFormat
,因此您可以重用identityserver4
提供的DistributedCacheStateDataFormatter
配置后类:
internal class ConfigureGoogleOptions : IPostConfigureOptions<GoogleOptions>
{
private string[] _schemes;
private readonly IHttpContextAccessor _httpContextAccessor;
public ConfigureGoogleOptions(string[] schemes, IHttpContextAccessor httpContextAccessor)
{
_schemes = schemes ?? throw new ArgumentNullException(nameof(schemes));
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}
public void PostConfigure(string name, GoogleOptions options)
{
// no schemes means configure them all
if (_schemes.Length == 0 || _schemes.Contains(name))
{
options.StateDataFormat = new DistributedCacheStateDataFormatter(_httpContextAccessor, name);
}
}
}
和注册帮助程序(将其添加到您自己的静态类中(:
public static IServiceCollection AddGoogleStateDataFormatterCache(this IServiceCollection services, params string[] schemes)
{
services.AddSingleton<IPostConfigureOptions<GoogleOptions>>(
svcs => new ConfigureGoogleOptions(
schemes,
svcs.GetRequiredService<IHttpContextAccessor>())
);
return services;
}