ASP.NET身份在ConfigureAuth之后更改ExpireTimeSpan

时间:2014-12-03 20:45:29

标签: c# asp.net owin asp.net-identity-2

我正在开发一个我最近从自定义身份验证解决方案迁移到ASP.NET身份的Web应用程序。在我们的应用程序的某些部分中,执行了长时间的过程,可能需要一个小时才能运行。在正常情况下,我们希望用户在30分钟的非活动后自动注销。但是,对于发生长进程的屏幕,我们希望扩展自动注销窗口,以便在进程完成之前不会被踢出。我目前正在努力解决如何使用Identity实现这一目标。我目前在Startup.Auth.cs文件中使用以下代码:

public partial class Startup
{
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the user manager and signin manager to use a single instance per request
        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("/Login.aspx"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30),
            SlidingExpiration = true,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity =
                    SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                        TimeSpan.FromMinutes(30),
                        (manager, user) => user.GenerateUserIdentityAsync(manager),
                        userIdentity => userIdentity.GetUserId<int>())
            }
        });
    }
}

我目前看不到在调用ConfigureAuth后修改ExpireTimeSpan值的方法。我希望能够从Web窗体页面更改Page_Load事件处理程序中的值。有谁知道一种方式?

1 个答案:

答案 0 :(得分:0)

内部OnValidateIdentity

又名:

OnValidateIdentity = delegate(CookieValidateIdentityContext context) {
            var stampValidator = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                getUserIdCallback: (id) => (id.GetUserId<int>())
            );
            Task result = stampValidator.Invoke(context);

            int my_custom_minutes = 60; // run your logic here.
                // set it at GLOBAL level for all (future) users.
                context.Options.ExpireTimeSpan = TimeSpan.FromMinutes( my_custom_minutes );
                // set it for the current user only.
                context.Properties.ExpiresUtc = context.Properties.IssuedUtc.Value.AddMinutes( my_custom_minutes );

            return result;
}