ネイティブ依存性注入コンテナを使用してCookie認証オプションを使用してASP.NetコアアプリケーションにCookie認証を追加するとします。起動後に実行時に認証オプションをどのように置き換えることができますか?たとえば、アプリの実行中にCookieの有効期限を変更する場合などです。変更に影響を与えるために、認証ハンドラとオプションの両方を置き換える方法を理解できません。認証を置き換えるために、実行時に実行時にCookie認証ハンドラスキームオプションを置換する
public static IServiceCollection ConfigureOAuth(this IServiceCollection services)
{
var appSettings = services.BuildServiceProvider().GetService<IOptions<AppSettings>>();
return services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
{
o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
})
.Services;
}
コード:起動時に
コード認証を追加する
/// <summary>
/// Replace authentication options with new ones read from configuration.
/// 1). Remove old services
/// 2.) Reload the configuration
/// 3.) Add the authentication scheme with options read from the latest configuration
/// </summary>
private static void ReplaceServices(IServiceCollection services, IHostingEnvironment env)
{
ClearServices(services);
services.Configure<AppSettings>(StartupConfiguration.BuildConfigurationRoot(env).GetSection("App"));
var provider = services.BuildServiceProvider();
var appSettings = provider.GetService<IOptions<AppSettings>>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
services.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(CookieAuthenticationDefaults.AuthenticationScheme, (o) =>
{
o.ExpireTimeSpan = TimeSpan.FromHours(appSettings.Value.HostOptions.SessionLifespanHours);
});
}
/// <summary>
/// Clear stale dependencies: application settings configured from appsettings.json,
/// authentication options and cookie authentication handler and options
/// </summary>
private static void ClearServices(IServiceCollection services)
{
var staleTypes = new List<Type>
{
typeof(IConfigureOptions<AppSettings>),
typeof(IConfigureOptions<AuthenticationOptions>),
typeof(IPostConfigureOptions<CookieAuthenticationOptions>),
typeof(IConfigureOptions<CookieAuthenticationOptions>),
typeof(CookieAuthenticationHandler)
};
foreach (var staleType in staleTypes)
{
var staleService = services.FirstOrDefault(s => s.ServiceType.Equals(staleType));
services.Remove(staleService);
}
}