x个小时不活动后的身份注销用户

时间:2019-01-07 15:58:54

标签: c# asp.net-mvc asp.net-identity

我的asp.net MVC网站同时使用了会话和Cookie。

如果用户角色为xyz,我必须保持用户登录15小时,否则在闲置5分钟后注销用户。

我的代码是:

web.config

<system.web>
   <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" slidingExpiration="true" cookieless="UseCookies" />
    </authentication>
      <sessionState timeout="5" />
</system.web>

AccountController

public ActionResult Login(LoginModel model)
{
    //validate data
    SignInManager.SignIn(user, true, true); 
    if(userRole = 'xyz')
         Session.Timeout = 900; //15 hours
}

对于(startup.auth.cs)中的cookie:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
         Provider = new CookieAuthenticationProvider
                {
                   OnValidateIdentity = async context =>
                    {
                        // invalidate user cookie if user's security stamp have changed, force logout user if its logout from any other device
                        var invalidateBySecirityStamp = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(0),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager));
                        await invalidateBySecirityStamp.Invoke(context);

                        bool xyzRole = false;

                        if (context.Identity != null)
                        {
                            xyzRole = context.Identity.Claims.Any(c => c.Type == ClaimTypes.Role && c.Value == 'xyz');
                        }

                        // check if enough time has passed to invalidate cookie
                        var currentUtc = DateTimeOffset.UtcNow;
                        if (context.Options != null && context.Options.SystemClock != null)
                        {
                            currentUtc = context.Options.SystemClock.UtcNow;
                        }
                        context.Properties.AllowRefresh = true;
                        if (xyzRole)
                        { //context.Properties.ExpiresUtc is always null
                            context.Properties.ExpiresUtc = currentUtc.AddMinutes(900);
                        }
                        else
                        {
                            context.Properties.ExpiresUtc = currentUtc.AddMinutes(5);
                        }
                    }
          }
    }
}

注意: 会话超时工作正常。因为如果会话过期,我将在函数Global.asax.cs的{​​{1}}中捕获它。

cookie迷惑无法正常运行,大约30分钟不活动后注销。

我做错了。

0 个答案:

没有答案