如何在ASP.NET Core中处理Cookie过期 [英] How to handle cookie expiration in asp.net core
问题描述
我想知道如何正确处理Cookie过期的事实?是否可以执行自定义操作?
I would like to know how to properly handle the fact that the cookie expired? Is it possible to execute a custom action ?
我想实现的是,当cookie过期时,将通过该信息重定向到操作参数,从而从当前cookie中获取很少的信息.有可能吗?
What I would like to achieve is that when the cookie is expired is to take few informations out of the current cookie at redirect to a action parametrise by this information. Is it possible ?
推荐答案
Looks like you need your own handler for OnValidatePrincipal event when setuping cokies auth middleware:
OnValidatePrincipal 事件可用于拦截和覆盖cookie身份验证
OnValidatePrincipal event can be used to intercept and override validation of the cookie identity
app.UseCookieAuthentication(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = <your event handler>
};
});
文档包含此类句柄的示例:
Documentation contains example of such handle:
public static class LastChangedValidator
{
public static async Task ValidateAsync(CookieValidatePrincipalContext context)
{
// Pull database from registered DI services.
var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
var userPrincipal = context.Principal;
// Look for the last changed claim.
string lastChanged;
lastChanged = (from c in userPrincipal.Claims
where c.Type == "LastUpdated"
select c.Value).FirstOrDefault();
if (string.IsNullOrEmpty(lastChanged) ||
!userRepository.ValidateLastChanged(userPrincipal, lastChanged))
{
context.RejectPrincipal();
await context.HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
}
}
}
这篇关于如何在ASP.NET Core中处理Cookie过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!