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

落花浮王杯 提交于 2020-01-01 04:05:08

问题


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 void ConfigureAuth(IAppBuilder app)
    {
        var timeoutInMinutes = int.Parse(ConfigurationManager.AppSettings["cookie.timeout-minutes"]);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            AuthenticationMode = AuthenticationMode.Active,
            LoginPath = new PathString("/"),
            ExpireTimeSpan = TimeSpan.FromMinutes(timeoutInMinutes),
            SlidingExpiration = true,
            LogoutPath = new PathString("/Sessions/Logout")
        });
    }
}

We have a feature request to allow our application's admins to customize session timeouts within their organizations. However, the configuration code above executes at the MVC application level and our app is multi-tenant. Does anyone know of a way to set the ExpireTimeSpan of a user's session on a per-user basis, either during authentication or by overriding an Owin pipeline event somewhere?

Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/28376285/is-it-possible-to-set-an-asp-net-owin-security-cookies-expiretimespan-on-a-per

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!