Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Automatic Logoff

Tags:

c#

asp.net-mvc

In my application I want to log the user off after a period of inactivity. Users log in using their Google account.

In the Web.config file, I put <sessionState mode="InProc" timeout="10" /> under <system.web>, however after 10 mins, the user was not logged off.

Another thing I would like the auto log off to do is to execute a piece of code before completing the log off. This code simply updates a field in a database table. I don't want to use JavaScript because I want the auto log off to work if the user navigates away from the website.

EDIT

Code inside Startup.Auth.cs as requested by @Igor

using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using StudentLive.Models;

namespace StudentLive
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                ClientSecret = "XXXXXXXXXXXXXXXXXXXX"
            });
        }
    }
}
like image 698
RoyalSwish Avatar asked Mar 12 '23 08:03

RoyalSwish


1 Answers

You need to modify the CookieAuthenticationOptions instance and provide additional details for your expiration.

From the documentation

  • SlidingExpiration - The SlidingExpiration is set to true to instruct the middleware to re-issue a new cookie with a new expiration time any time it processes a request which is more than halfway through the expiration window.
  • ExpireTimeSpan - Controls how much time the cookie will remain valid from the point it is created. The expiration information is in the protected cookie ticket. Because of that an expired cookie will be ignored even if it is passed to the server after the browser should have purged it.

Code:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    // add these lines
    SlidingExpiration = true,
    ExpireTimeSpan = TimeSpan.FromMinutes(10),
    // rest of your code
}
like image 148
Igor Avatar answered Mar 24 '23 18:03

Igor