在不删除应用程序cookie的情况下使ASP.NET Identity 2.0登录失效

时间:2015-11-16 19:33:34

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

背景

我正在处理的应用程序正在几个不同的域上运行,所有域都共享相同的数据库和IIS进程。用户可以通过单击链接在这些域之间切换,并且在执行此操作时应保持登录状态。为此,在单击切换域链接时,我在数据库中创建一个条目,该条目包含Identity 2应用程序cookie的当前值(默认情况下名为.AspNet.ApplicationCookie)。然后将用户重定向到新域,其中cookie的值从数据库中提取并在该域上设置。

此技术正在运行,但问题是注销一个域并不会将用户注销到其他域上,因为cookie只会从用户在登录时遇到的域中清除出。

问题

有没有办法在注销时使应用程序cookie无效,这样当它在仍然存在的域上读取时(可能是在尝试授权请求时),它将被忽略并且从该域中删除,要求用户再次登录?

我已尝试在OnValidateIdentity配置中取消注释并设置CookieAuthentication回调。听起来这可能与我想做的事情有关,但似乎并没有自己做任何事情。

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/"),
    CookieName = ApplicationCookieKey, // a string constant
    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, User, Guid>(
            validateInterval: TimeSpan.FromSeconds(1),
            getUserIdCallback: ((identity) => { return identity.GetUserId(); } ),
            regenerateIdentityCallback: async (manager, user) => await manager.GenerateUserIdentityAsync(user))
    },
});

GenerateUserIdentityAsync方法:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(User user)
{
    // Note the authenticationType must match the one 
    // defined in CookieAuthenticationOptions.AuthenticationType
    var userIdentity = await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    // Add custom user claims here
    return userIdentity;
}

1 个答案:

答案 0 :(得分:1)

  

我尝试取消注释并设置OnValidateIdentity回调   在CookieAuthentication配置中。听起来像这样   可能与我想做的事情有关,但似乎没有做任何事情   独自一人。

仅在SecurityStamp更新时触发。否则它什么都不做。您可以通过调用userManager.UpdateSecurityStamp()

手动触发它