如何在Identity 2.0中更新ApplicationCookie的超时

时间:2016-02-12 23:09:48

标签: angularjs asp.net-mvc asp.net-mvc-5 owin asp.net-identity-2

有没有办法在特定网络请求中续订Cookie的身份验证超时?我在我的MVC 5项目之上有一个Angular应用程序,我需要它来保持我的服务器会话在请求之间保持活跃状态​​。我有Angular部分工作,但似乎在我的服务器上点击URL不足以重置Auth超时。我是Identity的新手,所以我可能错过了一些简单的东西?

我的Startup.Auth.cs代码:

public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        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
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            ExpireTimeSpan = TimeSpan.FromSeconds(30),
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(20),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
    }

我的简单方法(全局为所有没有[AllowAnonymous]的请求设置授权):

    [HttpGet]
    public HttpResponseMessage KeepAuthAlive()
    {
        // Renew Auth Cookie - how?
    }

1 个答案:

答案 0 :(得分:1)

重新登录用户(此代码假定您根据默认的帐户控制器和异步ActionResult使用UserManager和SignInManager)。我没有对此进行过测试,但它应该会有效:

ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}