locked
OWIN Authentication, ExpireTimeSpan not working RRS feed

  • Question

  • User-1105411633 posted

    Hi ,

    I am using Owin Authentication. I want my application to redirect to login page after specified time. So i have set the expiration time in CookieAuthenticationOptions.

    Here is my code.

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
           ExpireTimeSpan = TimeSpan.FromMinutes(2.0),
           SlidingExpiration = false
    });

    I am able to browse through the application even after 2 mins  of login and no login page redirection is seen .

    My code is similar to the thread "OWIN Authentication and timeout with redirection". I have tried the fix in this thread but it didn't work.

    Monday, May 22, 2017 10:27 AM

Answers

  • User-1105411633 posted

    Hello EvenMa,

    Found the solution for the issue through BrockAllens  article https://brockallen.com/2014/11/18/sliding-and-absolute-expiration-with-cookie-authentication-middleware/ . While debugging,  in to the context dictionary found 5 properties already set. Those included AllowRefresh, ExpiresUtc, IsPersistent ,IssuedUtc and RedirectUri.

    //Overriding the default session time out and enabling sliding expiration
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    Provider = new CookieAuthenticationProvider
                    {
                        OnResponseSignIn = context =>
                        {
                            context.Properties.AllowRefresh = true;
                            context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(13);
                        }
                    }
                });

    Overriding the context properties fixed my issue. By default AllowRefresh was false and ExpiresUtc is set to 1 hour.

    Previously When i said   it is redirecting to login page while we are still browsing and that too, not at regular intervals.   i was wrong, it was due to default settings i.e AllowRefresh (false) and expireutc being set to 1 hour.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 30, 2017 9:50 AM

All replies

  • User-271186128 posted

    Hi ChenArc,

    According to your code, you didn't set the LoginPath and AuthenticationType, are you sure your app was working well?

    I suggest you could modify it like this:

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

    Best regards,
    Dillion

    Tuesday, May 23, 2017 6:52 AM
  • User-1105411633 posted

    Thanks for your inputs.

    Yes. The application is working absolutely fine. The issue is, it is redirecting to login page while we are still browsing and that too, not at regular intervals. We didn't set  any specific time out in the app. So we have assumed that it is taking session time out (20 mins) and logging out of application.

    I have checked application cookies in chrome and found these.

    Name Val Domain Path Expires /Max age Size
    .AspNet.Cookies some value localhost / Session 1210
    UserDetails some value localhost / 2017-05-23T16:22:03.585Z 4

    When i deleted the ".AspNet.Cookies" cookie manually( by clearing cookies), i am taken to the log-in page. What i want is to change the "Session" under expires to a time which i can configure in the app.

    I have added the login path but that too didn't  work. We are also using ADFS authentication. Here is the complete code.

    public void ConfigureAuth(IAppBuilder app)
    {
    
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
    ExpireTimeSpan = TimeSpan.FromMinutes(2.0),
    SlidingExpiration = false
    
    });
    
    if (AppConfiguration.UseOpenIdConnectAuthentication)
    {
    app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
    
    ClientId = AppConfiguration.ClientId,
    Authority = Authority,
    PostLogoutRedirectUri = AppConfiguration.PostLogoutRedirectUri,// Home/index where login credentials are entered
    
    Notifications = new OpenIdConnectAuthenticationNotifications
    {
    //
    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
    //
    
    AuthorizationCodeReceived = context =>
    {
    var code = context.Code;
    var credential = new ClientCredential(AppConfiguration.ClientId, AppConfiguration.AppKey);
    string userObjectId = context.AuthenticationTicket.Identity.FindFirst(AppConstants.ClaimObjectIdentifier).Value;
    var authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId));
    var result = authContext.AcquireTokenByAuthorizationCode(
    code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, AppConfiguration.GraphUrl);
    //AuthenticationHelper.token = result.AccessToken;
    return Task.FromResult(0);
    }
    }
    });
    
    }
    //configure Assurance ADFS middleware
    var adfs = new WsFederationAuthenticationOptions
    {
    MetadataAddress = AppConfiguration.MetadataAddress,
    AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
    AuthenticationMode = AuthenticationMode.Passive,
    Wreply = AppConfiguration.Wreply,
    SignOutWreply = AppConfiguration.Wreply,
    Wtrealm = AppConfiguration.Wreply
    };
    
    //add to pipeline
    app.UseWsFederationAuthentication(adfs );
    
    }


    Please let me know what i am missing.

    Thanks

    Archana

    Tuesday, May 23, 2017 8:51 AM
  • User1967761114 posted

    Hi ChenArc,

    It seems that has no error with your code.

    See the following code  which you provided:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
      ExpireTimeSpan = TimeSpan.FromMinutes(2.0),
      SlidingExpiration = false
    });

    When SlidingExpiration set to false, that mean the authentication will always invalid after 2 minutes.

    When SlidingExpiration set to true, that mean the  authentication will invalid if the user has no communicate with the server within 2 minutes.

    ChenArc

    it is redirecting to login page while we are still browsing and that too, not at regular intervals. 

    That’s so strange on not at regular intervals ,I’m not sure why, you could try to set SlidingExpiration to true , and then the authentication will invalid if the user has no communicate with the server within specify time.

    Or you could check dose it occurred by some fixed operations?

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Saturday, May 27, 2017 2:21 AM
  • User-1105411633 posted

    Hello EvenMa,

    Found the solution for the issue through BrockAllens  article https://brockallen.com/2014/11/18/sliding-and-absolute-expiration-with-cookie-authentication-middleware/ . While debugging,  in to the context dictionary found 5 properties already set. Those included AllowRefresh, ExpiresUtc, IsPersistent ,IssuedUtc and RedirectUri.

    //Overriding the default session time out and enabling sliding expiration
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    Provider = new CookieAuthenticationProvider
                    {
                        OnResponseSignIn = context =>
                        {
                            context.Properties.AllowRefresh = true;
                            context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(13);
                        }
                    }
                });

    Overriding the context properties fixed my issue. By default AllowRefresh was false and ExpiresUtc is set to 1 hour.

    Previously When i said   it is redirecting to login page while we are still browsing and that too, not at regular intervals.   i was wrong, it was due to default settings i.e AllowRefresh (false) and expireutc being set to 1 hour.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 30, 2017 9:50 AM