ASP.NET Identity注销另一个用户

时间:2014-12-07 05:48:13

标签: c# asp.net-web-api asp.net-identity

就像在这个question中一样,我想通过更新安全标记来注销另一个用户。但是,在本地计算机上进行测试时,它不起作用。我怀疑问题可能在于我用来重置用户并将不同属性保存到数据库的命令顺序。

这是我的Startup.Auth

public partial class Startup
{
    public static TimeSpan expireTimeSpan = TimeSpan.FromHours(24);
    public static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            ExpireTimeSpan = expireTimeSpan,
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        DataProtectionProvider = app.GetDataProtectionProvider();
    }
}

这是一种控制器方法,允许更改其他用户的电子邮件==用户名。在更改电子邮件时,用户应该已注销,并且不再拥有有效密码。

public async Task<IHttpActionResult> UpdateUser(string id, ApplicationUser newUser)
{
    var user = await _userManager.FindByIdAsync(id);
    if (user == null) ...

    IdentityResult result;

    user.name = newUser.name;
    user.roles = newUser.roles;

    // sign out user and invalidate password
    if (user.email != newUser.email)
    {
        user.email = newUser.email;
        user.PasswordHash = null;

        result = await _userManager.UpdateSecurityStampAsync(user.Id);
        if (!result.Succeeded) throw new Exception("Security Stamp not updated.");

        await _account.SendPasswordEmail(user);
    }

    result = await _userManager.UpdateAsync(user);
    if (!result.Succeeded)
        return GetErrorResult(result);

    return Ok();
}

我已经尝试先保留用户,然后生成新的SecurityStamp,但这也不起作用。

任何想法可能出错?

谢谢!

1 个答案:

答案 0 :(得分:1)

显然你没有在你明确链接的问题中阅读答案。

// important to register UserManager creation delegate. Won't work without it
app.CreatePerOwinContext(UserManager.Create);

这在此进一步说明:

https://aspnetidentity.codeplex.com/workitem/2209

但是,你应该知道这个错误:

ExpireTimeSpan ignored after regenerateIdentity / validateInterval duration in MVC Identity (2.0.1)

这将在即将发布的Identity 2.2 / Owin 3.0版本中修复,但尚未最终确定。

https://aspnetidentity.codeplex.com/workitem/2347

另见本博客文章:

http://tech.trailmax.info/2014/08/cookieauthenticationprovider-and-user-session-invalidation-on-change-of-securitystamp/