4

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"
            });
        }
    }
}
5
  • 2
    Session State is not the Authentication state. These are 2 completely different things. Session is a way to persist state for a session, session being a clients interaction with the site. Authentication is to whom is the client known to the system. So modifications to this setting in the web.config have no influence on the authenticated state of a client. Commented May 9, 2016 at 14:28
  • If you want additional help you will have to provide how you are authenticating your users, I am assuming you are using an existing library or built in provider. If not you will have to provide code you have so far to do this. Commented May 9, 2016 at 14:29
  • @Igor Users are authenticated using their Google accounts. Visual Studio 2013 provides the code to handle External Provider log ins in the Startup.Auth.cs file, and the AccountController already has the code that handles the external log in. I haven't had to do any real set up with this apart from providing my ClientId and ClientSecret. Commented May 9, 2016 at 14:33
  • Ok, so you are probably using the Oauth google provider. You can probably handle/set the default timeout in the startup.auth.cs file. Maybe you can post the code in that file. Commented May 9, 2016 at 14:35
  • 1
    @Igor - and the battle continues on clarifying this distinction a decade after being introduced into the .NET framework :) Commented May 9, 2016 at 15:20

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Does that expire the external authentication cookie though? Or does that only work with asp.net authentication cookies?
@ErikFunkenbusch - as I understand it its your cookie (that is owned by that domain) containing the claims information. This cookie is then re-validated with every request to rebuild the authenticated identity so your app has authentication context. You should be able to set the expiration behavior in your app as the cookie itself contains standard expiration info (expiration date/time).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.