Skip to content

Commit 42b3fad

Browse files
authored
Add validation to ensure Cookie.Expiration is not set (#8967)
1 parent 91dcbd4 commit 42b3fad

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

src/Security/Authentication/Cookies/src/CookieExtensions.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder
2626
public static AuthenticationBuilder AddCookie(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action<CookieAuthenticationOptions> configureOptions)
2727
{
2828
builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>());
29+
builder.Services.AddOptions<CookieAuthenticationOptions>(authenticationScheme).Validate(o => o.Cookie.Expiration == null, "Cookie.Expiration is ignored, use ExpireTimeSpan instead.");
2930
return builder.AddScheme<CookieAuthenticationOptions, CookieAuthenticationHandler>(authenticationScheme, displayName, configureOptions);
3031
}
3132
}

src/Security/Authentication/test/CookieTests.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Microsoft.AspNetCore.TestHost;
1818
using Microsoft.AspNetCore.Testing.xunit;
1919
using Microsoft.Extensions.DependencyInjection;
20+
using Microsoft.Extensions.Options;
2021
using Xunit;
2122

2223
namespace Microsoft.AspNetCore.Authentication.Cookies
@@ -140,20 +141,15 @@ public async Task SignInCausesDefaultCookieToBeCreated()
140141
}
141142

142143
[Fact]
143-
public async Task CookieExpirationOptionIsIgnored()
144+
public void SettingCookieExpirationOptionThrows()
144145
{
145-
var server = CreateServerWithServices(s => s.AddAuthentication().AddCookie(o =>
146+
var services = new ServiceCollection();
147+
services.AddAuthentication().AddCookie(o =>
146148
{
147-
o.Cookie.Name = "TestCookie";
148-
// this is currently ignored. Users should set o.ExpireTimeSpan instead
149149
o.Cookie.Expiration = TimeSpan.FromDays(10);
150-
}), SignInAsAlice);
151-
152-
var transaction = await SendAsync(server, "http://example.com/testpath");
153-
154-
var setCookie = transaction.SetCookie;
155-
Assert.StartsWith("TestCookie=", setCookie);
156-
Assert.DoesNotContain("; expires=", setCookie);
150+
});
151+
var options = services.BuildServiceProvider().GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>();
152+
Assert.Throws<OptionsValidationException>(() => options.Get(CookieAuthenticationDefaults.AuthenticationScheme));
157153
}
158154

159155
[Fact]

0 commit comments

Comments
 (0)