Add validation to ensure Cookie.Expiration is not set (#8967)

This commit is contained in:
Hao Kung 2019-04-02 09:56:37 -07:00 committed by GitHub
parent 91dcbd44c1
commit 42b3fada31
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 11 deletions

View File

@ -26,6 +26,7 @@ namespace Microsoft.Extensions.DependencyInjection
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<CookieAuthenticationOptions> configureOptions)
{
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
builder.Services.AddOptions<CookieAuthenticationOptions>(authenticationScheme).Validate(o => o.Cookie.Expiration == null, "Cookie.Expiration is ignored, use ExpireTimeSpan instead.");
return builder.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
}
}

View File

@ -17,6 +17,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Cookies
@ -140,20 +141,15 @@ namespace Microsoft.AspNetCore.Authentication.Cookies
}
[Fact]
public async Task CookieExpirationOptionIsIgnored()
public void SettingCookieExpirationOptionThrows()
{
var server = CreateServerWithServices(s => s.AddAuthentication().AddCookie(o =>
var services = new ServiceCollection();
services.AddAuthentication().AddCookie(o =>
{
o.Cookie.Name = "TestCookie";
// this is currently ignored. Users should set o.ExpireTimeSpan instead
o.Cookie.Expiration = TimeSpan.FromDays(10);
}), SignInAsAlice);
var transaction = await SendAsync(server, "http://example.com/testpath");
var setCookie = transaction.SetCookie;
Assert.StartsWith("TestCookie=", setCookie);
Assert.DoesNotContain("; expires=", setCookie);
});
var options = services.BuildServiceProvider().GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>();
Assert.Throws<OptionsValidationException>(() => options.Get(CookieAuthenticationDefaults.AuthenticationScheme));
}
[Fact]