is there an event fires when user login cookie already expired?

Dondon510 221 Reputation points
2022-07-06T15:25:28.66+00:00

is there an event fires when user login cookie already expired?

below TimeSpan.FromMinutes(1); // Only in dev

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  
.AddCookie(options =>  
{  
    options.LoginPath = "/User/Login";  
    options.AccessDeniedPath = "/User/Login";  
    options.LogoutPath = "/User/Logout";  
    options.SlidingExpiration = true;  
    options.ExpireTimeSpan = TimeSpan.FromMinutes(1);  
});  

I expect to have an event firing when the cookie authentication expired, so I can put some process in there.

need advice

thank you

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2022-07-06T16:47:48.193+00:00

    no. after the cookie expires, the browser does not include the cookie with server requests.

    if you want an event, then you will need to create one. on each request, you will need to log the timestamp. when timestamp + cookie timeout > now, then fire the event.

    you could use a background service to do the monitoring and keep the list of users and their last access.

    note: if hosted in a webform, then a database and a scheduled job might make sense,

    0 comments No comments

  2. Dondon510 221 Reputation points
    2022-07-07T08:35:00.837+00:00

    I found this:

    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  
    .AddCookie(options =>  
    {  
        options.LoginPath = "/User/Login";  
        options.AccessDeniedPath = "/User/Login";  
        options.LogoutPath = "/User/Logout";  
        options.SlidingExpiration = true;  
        options.ExpireTimeSpan = TimeSpan.FromMinutes(1);  
        options.Events = new CookieAuthenticationEvents  
        {  
            OnCheckSlidingExpiration = OnCheckSlidingExpiration  
        };  
    });  
      
    Task OnCheckSlidingExpiration(CookieSlidingExpirationContext arg)  
    {  
        if (arg.ShouldRenew)  
        {  
             // I DON'T HAVE AN IDEA HERE. HOW TO NOTIFY THE USER  
        }  
        return Task.CompletedTask;  
    }  
    
    0 comments No comments

  3. Bruce (SqlWork.com) 61,731 Reputation points
    2022-07-07T16:55:51.48+00:00

    on sliding expiration, on each request if the request time is halfway to the expiration, the expiration is date is reset. so on the standard 20 minute cookie, if a request comes after the 10 minutes, the expiration is updated to now + 20 minutes. this callback allows canceling the updating the expiration, say you want to force a login after 60 minutes, then you would not allow the sliding login to set the expiration to more the start + 60

    anyway the event doesn't mean the ticket is expired, just that it will shortly. on expiration, the browser does not send a cookie, so it looks to the server like a new session.

    0 comments No comments

  4. SurferOnWww 2,491 Reputation points
    2022-07-07T01:02:30.397+00:00

    I reply assuming that you use the ASP.NET Core Identity.

    is there an event fires when user login cookie already expired?

    No, there is no such event. However, you will be able to use a middleware to examine if the authentication ticket has been expired. Shown below is a sample code:

    using System;  
    using System.Threading.Tasks;  
    using Microsoft.AspNetCore.Http;  
    using Microsoft.AspNetCore.Authentication.Cookies;  
    using Microsoft.Extensions.Options;  
    using Microsoft.AspNetCore.DataProtection;  
    using Microsoft.AspNetCore.Authentication;  
    using System.Security.Claims;  
    using System.Security.Principal;  
       
    namespace MvcCoreApp.Middleware  
    {  
        public class AuthExpireCheckMiddleware  
        {  
            private readonly RequestDelegate _next;  
            private readonly CookieAuthenticationOptions _options;  
       
            // obtain CookieAuthenticationOptions object by DI  
            public AuthExpireCheckMiddleware(  
                RequestDelegate next,  
                IOptions<CookieAuthenticationOptions> options)  
            {  
                _next = next;  
                _options = options.Value;  
            }  
       
            public async Task InvokeAsync(HttpContext context)  
            {  
                await _next.Invoke(context);  
       
                // check only if requested page is "Login"  
                // "/Identity/Account/Login" is default setting by Visual Studio  
                if (context.Request.Path.ToString().  
                                         Contains("/Identity/Account/Login"))  
                {  
                    // check only if auth cookie has been recieved  
                    // cookiew name ".AspNetCore.Identity.Application"is default  
                    // setting by Visual Studio  
                    string cookie   
                        = context.Request.Cookies[".AspNetCore.Identity.Application"];  
                    if (!string.IsNullOrEmpty(cookie))  
                    {  
                        IDataProtectionProvider provider =   
                            _options.DataProtectionProvider;  
                        IDataProtector protector = provider.CreateProtector(  
                            "Microsoft.AspNetCore.Authentication.Cookies." +  
                            "CookieAuthenticationMiddleware",  
                            "Identity.Application",  
                            "v2");  
       
                        // decriypt auth ticket in auth cookie  
                        TicketDataFormat format = new TicketDataFormat(protector);  
                        AuthenticationTicket authTicket = format.Unprotect(cookie);  
       
                        // get user name  
                        ClaimsPrincipal principal = authTicket.Principal;  
                        IIdentity identity = principal.Identity;  
                        string userName = identity.Name;  
       
                        // get expiration datetime of auth ticket  
                        AuthenticationProperties property = authTicket.Properties;  
                        DateTimeOffset? expiersUrc = property.ExpiresUtc;  
       
                        // check if auth ticket has been expired  
                        if (expiersUrc.Value < DateTimeOffset.UtcNow)  
                        {      
                            // do something to notify that auth ticket has been expired  
                        }  
                    }  
                }  
            }  
        }  
    }