Is it possible to set an ASP.NET Owin security cookie's ExpireTimeSpan on a per-user basis?

前端 未结 1 1976
青春惊慌失措
青春惊慌失措 2021-02-12 18:02

We have an ASP.NET MVC 5 app using Owin cookie authentication. Currently, we set up cookie authentication as follows:

public partial class Startup
{
    public v         


        
1条回答
  •  心在旅途
    2021-02-12 18:38

    The authentication options contains a property called Provider. You can either set this to the default provider and use one of the method overrides such as OnResponseSignIn to modify the settings of the login, or you could implement your own ICookieAuthenticationProvider and do the same.

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        Provider = new CookieAuthenticationProvider
        {
            OnResponseSignIn = signInContext =>
            {
                var expireTimeSpan = TimeSpan.FromMinutes(15);
    
                if (signInContext.Properties.Dictionary["organization"] == "org-1")
                {
                    expireTimeSpan = TimeSpan.FromMinutes(45);
                }
    
                signInContext.Properties.ExpiresUtc = DateTime.UtcNow.Add(expireTimeSpan);
            }
        }
    });
    

    You could either check the incoming claim to see how the session should be handled or you could add custom data to your sign in call.

    context.Authentication.SignIn(new AuthenticationProperties
    {
        Dictionary =
        {
            { "organization", "org-3" }
        }
    }, new ClaimsIdentity());
    

    You could even set ExpiresUtc on the sign in call if you really wanted, though it might be best to leave that logic in the authentication provider so it's easier to manage.

    0 讨论(0)
提交回复
热议问题