如何在asp.net core中处理cookie过期

Dav*_*ave 6 asp.net-mvc asp.net-identity asp.net-core-mvc asp.net-core

我想知道如何正确处理 cookie 过期的事实?是否可以执行自定义操作?

我想实现的是,当 cookie 过期时,在通过此信息重定向到动作参数时,从当前 cookie 中取出少量信息。是否可以 ?

Ash*_*Lee 5

没有一个好的方法可以实现这一点。如果 cookie 过期,则不会将其发送到服务器以提取任何信息。使用 ASP.Net Core Identity,您对此没有太多控制权。这样您就可以使用 Cookie 中间件了。

当 cookie 过期时,这为用户提供了正常的重定向:

public void ConfigureServices(IServiceCollection services)
{       
    services.Configure<CookieAuthenticationOptions>(options =>
    {
        options.LoginPath = new PathString("/Home/Index");
    });
}
Run Code Online (Sandbox Code Playgroud)

实现您所寻找的效果的最佳方法是将 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>
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


Set*_*Set 3

在设置 cookie 身份验证中间件时,您似乎需要自己的OnValidatePrincipal事件处理程序:

OnValidatePrincipal事件可用于拦截和覆盖 cookie 身份验证

app.UseCookieAuthentication(options =>
{
    options.Events = new CookieAuthenticationEvents
    {
        OnValidatePrincipal = <your event handler>
    };
});
Run Code Online (Sandbox Code Playgroud)

ASP.NET 文档包含此类处理程序的示例:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果 cookie 过期,它永远不会出现在 `OnValidatePrincipal` 中。 (14认同)