在Asp.Net Identity 2中非永久登录后的用户注销 [英] User logout after non-persistent login in Asp.Net Identity 2

查看:70
本文介绍了在Asp.Net Identity 2中非永久登录后的用户注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Asp.Net Identity 2.2配置为能够正常且永久地登录.我知道要考虑两个设置,即CookieAuthenticationProvider的validateInterval和CookieAuthenticationOptions的ExpireTimeSpan.这是一个新的MVC 5应用程序随附的标准配置,为了牢记它们,ExpireTimeSpan和SlidingExpiration明确设置为它们的默认值:

I am trying to configure Asp.Net Identity 2.2 to be able to login normally and permanently. I know there are two settings to get into account, the validateInterval of the CookieAuthenticationProvider and the ExpireTimeSpan of the CookieAuthenticationOptions. Here is the standard configuration which comes with a new MVC 5 application, with the ExpireTimeSpan and SlidingExpiration set explicitly to their default values just to have them in mind:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    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(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
    ExpireTimeSpan = TimeSpan.FromDays(14),
    SlidingExpiration = true,
});

每30分钟调用一次OnValidateIdentity,并检查用户的安全标记.如果尚未更改(例如,用户未更改密码),则不会发生任何事情-用户仍保持登录状态.没关系.

OnValidateIdentity is called every 30 minutes and checks the security stamp of the user. If it hasn't been changed (so e.g. the user has not changed his password), nothing happens - the user remains logged in. Which is OK.

如果我正常登录(非永久登录),则会创建一个cookie,该cookie的过期时间为在浏览器关闭时".因此,无法以任何方式控制注销时间,并且用户将保持登录状态,直到他/她关闭浏览器或进行使安全标记无效的更改(更改密码或电子邮件等)为止.

If I login normally (not-persistent) a cookie is created with expiration "on browser close". Thus the time of logout is not controlled in any way and the user remains logged in until he/she closes the browser or makes a change which invalidates the security stamp (change password or email, etc.).

如果我永久登录,将创建相同的cookie,但它在14天后过期(这是永久登录通常的工作方式,它不是永久"的,而是仅适用于一段时间).因此,只要用户每14天至少使用一次该应用程序,该用户就保持登录状态.

If I login persistently the same cookie is created but it has expiration in 14 days (which is how persistent login usually works, it is not "forever" but for some time only). So the user remains logged in as long as he/she uses the application at least once every 14 days.

我的问题是:如何使正常(非持久)登录在一段时间后过期,例如15分钟,即使用户没有关闭浏览器并且安全标记保持不变(等同于将浏览器保持打开状态15分钟)?如果将ExpireTimeSpan设置为15分钟,则所有会话(包括持久性会话)仅变为15分钟,这不是解决方案.

My question is: how can I make the normal (non-persistent) login to expire after some time, e.g. 15 minutes, even if the user does not close the browser and the security stamp remains unchanged (which is equivalent of leaving the browser open for 15 minutes)? If I set ExpireTimeSpan to 15 minutes all sessions (including persistent) become 15 minutes only which is not a solution.

推荐答案

我通过从SignInManager继承并添加新属性成功实现了这一点:

I succeeded to achieve this by inheriting from SignInManager, adding a new property:

/// <summary>
///     Defines how long a user session lasts if it is non persistent. A null value means until the browser is closed (default)
/// </summary>
public virtual TimeSpan? NonPersistentSessionDuration { get; set; }

并覆盖方法:

/// <summary>
/// Creates a user identity and then signs the identity using the AuthenticationManager
/// </summary>
/// <param name="user"></param>
/// <param name="isPersistent"></param>
/// <param name="rememberBrowser"></param>
/// <returns></returns>
public virtual async Task SignInAsync(TUser user, bool isPersistent, bool rememberBrowser)
{
    var userIdentity = await CreateUserIdentityAsync(user).WithCurrentCulture();
    // Clear any partial cookies from external or two factor partial sign ins
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);

    var properties = new AuthenticationProperties {IsPersistent = isPersistent};
    if (!isPersistent && this.NonPersistentSessionDuration != null)
        properties.ExpiresUtc = DateTimeOffset.UtcNow.Add(this.NonPersistentSessionDuration.Value);
    if (rememberBrowser)
    {
        var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
        AuthenticationManager.SignIn(properties, userIdentity, rememberBrowserIdentity);
    }
    else
    {
        AuthenticationManager.SignIn(properties, userIdentity);
    }
}

此更改是将AuthenticationProperties对象的ExpiresUtc属性设置为非持久登录.

The change is setting the ExpiresUtc property of the AuthenticationProperties object for non-persistent sign in.

当然,在SignInManager配置中,您必须将新的NonPersistentSessionDuration属性设置为某个值,该值将是非持久会话的会话长度.

Of course in the SignInManager configuration you have to set the new NonPersistentSessionDuration property to some value which will be the session length for non-persistent sessions.

这篇关于在Asp.Net Identity 2中非永久登录后的用户注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆