问题
I'm looking to set the .AspNetCore.Identity.Application
Cookie's expiration time based on the role of claims of a user that logs in.
In all of the configure options in ConfigureServices
I have access to cookie properties but no access to user claims. Therefore I cannot dynamically set the expiration time. We are using Microsoft.AspNetCore.Identity SignInManager
to authenticate.
Can anyone point me in the right direction as to what class I need to override or what middleware I need to register to achieve this?
回答1:
The Cookie Authentication Handler will trigger OnSigningIn
event before generating an authentication ticket, see source code on GitHub :
protected async override Task HandleSignInAsync(ClaimsPrincipal user, AuthenticationProperties properties)
{
// ...
if (!signInContext.Properties.ExpiresUtc.HasValue)
{
signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan);
}
await Events.SigningIn(signInContext);
if (signInContext.Properties.IsPersistent)
{
var expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan);
signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime();
}
var ticket = new AuthenticationTicket(signInContext.Principal, signInContext.Properties, signInContext.Scheme.Name);
// ...
}
(Note the line await Events.SigningIn(signInContext);
)
This gives us a chance to modify the expiration time using Events.OnSigningIn
. So in your ConfigureServices()
method, add codes as below :
services.ConfigureApplicationCookie(opt =>{
opt.Events.OnSigningIn = async(signinContext)=>{
// you can use the pricipal to query claims and roles as you need
var x = signinContext.Principal.Claims.First(c=>c.Type=="X1" && ...);
// set the expiration time according to claims/roles dynamically
signinContext.Properties.ExpiresUtc = DateTimeOffset.Now.AddSeconds(100);
signinContext.CookieOptions.Expires = signinContext.Properties.ExpiresUtc?.ToUniversalTime();
};
});
It will work as expected.
来源:https://stackoverflow.com/questions/52952488/how-to-set-aspnetcore-identity-application-cookies-expiration-based-on-identity