Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set TimeOut for OwinContext in MVC 5

When a user access a website and enters their credentials which are stored in our database, we when create an authentication.

How do you set the timeout? Using MVC 5.

My Authentication looks like this:

        var claims = new List<Claim>();
        claims.Add(new Claim("UserId", user.UserID.ToString()));
        claims.Add(new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName));
        claims.Add(new Claim(ClaimTypes.Email, user.Email));
        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()));
        var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignIn(id); 
like image 630
DavidJS Avatar asked Apr 08 '14 18:04

DavidJS


People also ask

How can increase session timeout in ASP NET MVC 5?

Open the web. config file, then increase the value in minutes by using the time out attribute of SessionState element. By default, the session timeout value is 20 minutes. Also in your case if you are using forms authentication, please check the timeout value.

How session timeout works in ASP NET MVC?

In web applications, session holds the information of current logged-in users. So, if the session expires in 20 minutes, then it is redirected to login page. In that case, we need to check if session exists (not null) in every action/ every controller which requires authentication.


1 Answers

The way to set an fixed expiration time span is to set the ExpireTimeSpan property in your Startup.Auth.cs file like this:

// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    ExpireTimeSpan = TimeSpan.FromDays(2)
});

Note that you'll also have to set the cookie to persist. In your code you'll have to pass in a bool in addition to the username and password, and then change

authenticationManager.SignIn(id); 

to be

authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, id); 
like image 106
Dave Avatar answered Oct 02 '22 17:10

Dave