How to handle cookie expiration in asp.net core

后端 未结 3 1473
青春惊慌失措
青春惊慌失措 2021-02-10 02:47

I would like to know how to properly handle the fact that the cookie expired? Is it possible to execute a custom action ?

What I would like to achieve is that when the c

3条回答
  •  我寻月下人不归
    2021-02-10 03:00

    Looks like you need your own handler for OnValidatePrincipal event when setuping cokies auth middleware:

    OnValidatePrincipal event can be used to intercept and override validation of the cookie identity

    app.UseCookieAuthentication(options =>
    {
        options.Events = new CookieAuthenticationEvents
        {
            OnValidatePrincipal = 
        };
    });
    

    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();
            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");
            }
        }
    }
    

提交回复
热议问题