-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Add a new OnCheckSlidingExpiration event to control renewal #33016
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
9 changes: 2 additions & 7 deletions
9
src/Security/Authentication/Cookies/samples/CookieSample/CookieSample.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,13 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFrameworks>$(DefaultNetCoreTargetFramework)</TargetFrameworks> | ||
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.AspNetCore" /> | ||
<Reference Include="Microsoft.AspNetCore.Authentication.Cookies" /> | ||
<Reference Include="Microsoft.AspNetCore.Hosting" /> | ||
<Reference Include="Microsoft.AspNetCore.DataProtection" /> | ||
<Reference Include="Microsoft.AspNetCore.Server.IISIntegration" /> | ||
<Reference Include="Microsoft.AspNetCore.Server.Kestrel" /> | ||
<Reference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" /> | ||
<Reference Include="Microsoft.Extensions.Logging.Console" /> | ||
</ItemGroup> | ||
|
||
</Project> |
91 changes: 66 additions & 25 deletions
91
src/Security/Authentication/Cookies/samples/CookieSample/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,73 @@ | ||
using System.IO; | ||
using System; | ||
using System.Linq; | ||
using System.Security.Claims; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Hosting; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.AspNetCore.Authentication; | ||
using Microsoft.AspNetCore.Authentication.Cookies; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.DependencyInjection; | ||
|
||
namespace CookieSample | ||
{ | ||
public static class Program | ||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
builder.Services | ||
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) | ||
.AddCookie(options => | ||
{ | ||
public static Task Main(string[] args) | ||
options.ExpireTimeSpan = TimeSpan.FromSeconds(20); | ||
options.Events = new CookieAuthenticationEvents() | ||
{ | ||
var host = new HostBuilder() | ||
.ConfigureWebHost(webHostBuilder => | ||
{ | ||
webHostBuilder | ||
.UseKestrel() | ||
.UseContentRoot(Directory.GetCurrentDirectory()) | ||
.UseIISIntegration() | ||
.UseStartup<Startup>(); | ||
}) | ||
.ConfigureLogging(factory => | ||
OnCheckSlidingExpiration = context => | ||
{ | ||
// If 25% expired instead of the default 50%. | ||
context.ShouldRenew = context.ElapsedTime > (context.Options.ExpireTimeSpan / 4); | ||
|
||
// Don't renew on API endpoints that use JWT. | ||
var authData = context.HttpContext.GetEndpoint()?.Metadata.GetMetadata<IAuthorizeData>(); | ||
if (authData != null && string.Equals(authData.AuthenticationSchemes, "Bearer", StringComparison.Ordinal)) | ||
{ | ||
factory.AddConsole(); | ||
factory.AddFilter("Console", level => level >= LogLevel.Information); | ||
}) | ||
.Build(); | ||
context.ShouldRenew = false; | ||
} | ||
|
||
return Task.CompletedTask; | ||
} | ||
}; | ||
}); | ||
|
||
var app = builder.Build(); | ||
|
||
app.UseAuthentication(); | ||
|
||
app.MapGet("/", async context => | ||
{ | ||
if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) | ||
{ | ||
var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme)); | ||
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user); | ||
|
||
return host.RunAsync(); | ||
} | ||
context.Response.ContentType = "text/plain"; | ||
await context.Response.WriteAsync("Hello First timer"); | ||
return; | ||
} | ||
} | ||
|
||
context.Response.ContentType = "text/plain"; | ||
await context.Response.WriteAsync("Hello old timer"); | ||
}); | ||
|
||
app.MapGet("/ticket", async context => | ||
{ | ||
var ticket = await context.AuthenticateAsync(); | ||
if (!ticket.Succeeded) | ||
{ | ||
await context.Response.WriteAsync($"Signed Out"); | ||
return; | ||
} | ||
|
||
foreach (var (key, value) in ticket.Properties.Items) | ||
{ | ||
await context.Response.WriteAsync($"{key}: {value}\r\n"); | ||
} | ||
}); | ||
|
||
app.Run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 0 additions & 45 deletions
45
src/Security/Authentication/Cookies/samples/CookieSample/Startup.cs
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -80,7 +80,7 @@ private Task<AuthenticateResult> EnsureCookieTicket() | |
return _readCookieTask; | ||
} | ||
|
||
private void CheckForRefresh(AuthenticationTicket ticket) | ||
private async Task CheckForRefreshAsync(AuthenticationTicket ticket) | ||
{ | ||
var currentUtc = Clock.UtcNow; | ||
var issuedUtc = ticket.Properties.IssuedUtc; | ||
|
@@ -91,7 +91,13 @@ private void CheckForRefresh(AuthenticationTicket ticket) | |
var timeElapsed = currentUtc.Subtract(issuedUtc.Value); | ||
var timeRemaining = expiresUtc.Value.Subtract(currentUtc); | ||
|
||
if (timeRemaining < timeElapsed) | ||
var eventContext = new CookieSlidingExpirationContext(Context, Scheme, Options, ticket, timeElapsed, timeRemaining) | ||
{ | ||
ShouldRenew = timeRemaining < timeElapsed, | ||
}; | ||
await Options.Events.OnCheckSlidingExpiration(eventContext); | ||
|
||
if (eventContext.ShouldRenew) | ||
{ | ||
RequestRefresh(ticket); | ||
} | ||
|
@@ -174,8 +180,6 @@ private async Task<AuthenticateResult> ReadCookieTicket() | |
return AuthenticateResult.Fail("Ticket expired"); | ||
} | ||
|
||
CheckForRefresh(ticket); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I moved this to clarify that it's only relevant to Authenticate scenarios. SignIn and SignOut also call ReadCookieTicket, but only to populate the _sessionKey. |
||
|
||
// Finally we have a valid ticket | ||
return AuthenticateResult.Success(ticket); | ||
} | ||
|
@@ -189,6 +193,10 @@ protected override async Task<AuthenticateResult> HandleAuthenticateAsync() | |
return result; | ||
} | ||
|
||
// We check this before the ValidatePrincipal event because we want to make sure we capture a clean clone | ||
// without picking up any per-request modifications to the principal. | ||
await CheckForRefreshAsync(result.Ticket); | ||
|
||
Debug.Assert(result.Ticket != null); | ||
var context = new CookieValidatePrincipalContext(Context, Scheme, Options, result.Ticket); | ||
await Events.ValidatePrincipal(context); | ||
|
53 changes: 53 additions & 0 deletions
53
src/Security/Authentication/Cookies/src/CookieSlidingExpirationContext.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// Copyright (c) .NET Foundation. All rights reserved. | ||
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. | ||
|
||
using System; | ||
using Microsoft.AspNetCore.Http; | ||
|
||
namespace Microsoft.AspNetCore.Authentication.Cookies | ||
{ | ||
/// <summary> | ||
/// Context object passed to the CookieAuthenticationEvents OnCheckSlidingExpiration method. | ||
/// </summary> | ||
public class CookieSlidingExpirationContext : PrincipalContext<CookieAuthenticationOptions> | ||
{ | ||
/// <summary> | ||
/// Creates a new instance of the context object. | ||
/// </summary> | ||
/// <param name="context"></param> | ||
/// <param name="scheme"></param> | ||
/// <param name="ticket">Contains the initial values for identity and extra data</param> | ||
/// <param name="elapsedTime"></param> | ||
/// <param name="remainingTime"></param> | ||
/// <param name="options"></param> | ||
public CookieSlidingExpirationContext(HttpContext context, AuthenticationScheme scheme, CookieAuthenticationOptions options, | ||
AuthenticationTicket ticket, TimeSpan elapsedTime, TimeSpan remainingTime) | ||
: base(context, scheme, options, ticket?.Properties) | ||
{ | ||
if (ticket == null) | ||
{ | ||
throw new ArgumentNullException(nameof(ticket)); | ||
} | ||
|
||
Principal = ticket.Principal; | ||
ElapsedTime = elapsedTime; | ||
RemainingTime = remainingTime; | ||
} | ||
|
||
/// <summary> | ||
/// The amount of time that has elapsed since the cookie was issued or renewed. | ||
/// </summary> | ||
public TimeSpan ElapsedTime { get; } | ||
|
||
/// <summary> | ||
/// The amount of time left until the cookie expires. | ||
/// </summary> | ||
public TimeSpan RemainingTime { get; } | ||
|
||
/// <summary> | ||
/// If true, the cookie will be renewed. The initial value will be true if the elapsed time | ||
/// is greater than the remaining time (e.g. more than 50% expired). | ||
/// </summary> | ||
public bool ShouldRenew { get; set; } | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
src/Security/Authentication/Cookies/src/PublicAPI.Unshipped.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You could consider moving this to auth samples instead of manual and adding a test for this scenario (always nicer to have coverage)
https://github.com/dotnet/aspnetcore/blob/main/src/Security/test/AuthSamples.FunctionalTests/CookiesTests.cs
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I mainly wanted to show @brockallen that there were other patterns than matching request paths.