기본 종속성 주입 컨테이너를 사용하여 쿠키 인증 옵션을 사용하여 ASP.Net 핵심 응용 프로그램에 쿠키 인증을 추가하는 경우. 시작 후 실행시 인증 옵션을 어떻게 대체 할 수 있습니까? 예를 들어 앱이 실행되는 동안 쿠키 만료를 변경하려고합니다. 변경에 영향을 미치기 위해 인증 처리자를 옵션으로 대체하는 방법을 알 수 없습니다. 인증을 대체하기 위해 런타임에런타임에 쿠키 인증 처리기 스키마 옵션 바꾸기
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);
}
}