【发布时间】:2016-12-17 19:51:25
【问题描述】:
我想知道如何正确处理cookie过期的事实?是否可以执行自定义操作?
我想要实现的是,当 cookie 过期时,在通过该信息重定向到操作参数时,从当前 cookie 中提取少量信息。有可能吗?
【问题讨论】:
标签: asp.net-mvc asp.net-core asp.net-identity asp.net-core-mvc
我想知道如何正确处理cookie过期的事实?是否可以执行自定义操作?
我想要实现的是,当 cookie 过期时,在通过该信息重定向到操作参数时,从当前 cookie 中提取少量信息。有可能吗?
【问题讨论】:
标签: asp.net-mvc asp.net-core asp.net-identity asp.net-core-mvc
没有很好的方法来实现这一点。如果 cookie 过期,则不会将其发送到服务器以提取任何信息。使用 ASP.Net Core Identity,您对此没有太多控制权。这让您可以使用 Cookie 中间件。
这会在 cookie 过期时为用户提供正常的重定向:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookieAuthenticationOptions>(options =>
{
options.LoginPath = new PathString("/Home/Index");
});
}
实现您正在寻找的最佳方法是将 cookie 过期设置为远晚于真正的用户会话过期,然后在服务器端执行会话过期并在该点重定向用户。虽然不理想,但当 cookie 过期时,您没有其他选择。
public void ConfigureServices(IServiceCollection services)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
// Redirect when cookie expired or not present
LoginPath = new PathString("/Account/Unauthorized/"),
AutomaticAuthenticate = true,
// never expire cookie
ExpireTimeSpan = TimeSpan.MaxValue,
Events = new CookieAuthenticationEvents()
{
// in custom function set the session expiration
// via the DB and reset it everytime this is called
// if the session is still active
// otherwise, you can redirect if it's invalid
OnValidatePrincipal = <custom function here>
}
});
}
【讨论】:
在设置 cookie 身份验证中间件时,您似乎需要自己的 OnValidatePrincipal 事件处理程序:
OnValidatePrincipal 事件可用于拦截和覆盖 cookie 身份验证
app.UseCookieAuthentication(options =>
{
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = <your event handler>
};
});
ASP.NET documentation 包含此类处理程序的示例:
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");
}
}
}
【讨论】:
OnValidatePrincipal 中。
您的情况似乎没有任何事件,但您可以使用 OnRedirectToLogin 更改重定向 uri。这是一个例子:
OnRedirectToLogin = async (context) =>
{
var binding = context.HttpContext.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
var tlsTokenBinding = binding == null ? null : Convert.ToBase64String(binding);
var cookie = context.Options.CookieManager.GetRequestCookie(context.HttpContext, context.Options.CookieName);
if (cookie != null)
{
var ticket = context.Options.TicketDataFormat.Unprotect(cookie, tlsTokenBinding);
var expiresUtc = ticket.Properties.ExpiresUtc;
var currentUtc = context.Options.SystemClock.UtcNow;
if (expiresUtc != null && expiresUtc.Value < currentUtc)
{
context.RedirectUri += "&p1=yourparameter";
}
}
context.HttpContext.Response.Redirect(context.RedirectUri);
}
【讨论】: