简体   繁体   中英

How to stop extending cookie expiration time for ajax calls?

I set ExpireTimeSpan to one day ,but i have notification service in the UI that send ajax call each 5 minutes ,so the ajax call will extend the expiration time ,as result of that the system will not logout after period of time if the user is in active ,how could i resolve that

        int expireTime = 1440; //one day

        app.UseCookieAuthentication(new CookieAuthenticationOptions
         {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(expireTime),
            SlidingExpiration=true, 
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

i found this solution for asp.net core : https://medium.com/cacti-pins/conditionally-set-sliding-expiration-time-on-authentication-cookies-in-asp-net-core-e70ffe7da49d but i'm using .net4.5

I don't think there is a particularly simple solution to this issue, but there are a couple of avenues you could look at.

First of all you could consider using WebSockets for the notification service. In a C# application it would seem sensible to use SignalR . This will allow you to open a persistent connection between client and server and enable a server push, which should only involve sending the cookie on the initial connection. Beware that by default SignalR can downgrade to long polling if other options are not supported within the browser which would still suffer from the same issue.

Alternatively you could look at swapping the ajax call for a javascript fetch() . This will allow you to omit the cookie when you make a request. You will however need to generate an alternative Authorization token within your application and manage this. You may also need to move the notification service into its own application so that it is not using the same authentication scheme.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM