如何取消当前用户ASP.net mvc身份的身份验证

时间:2019-05-06 20:51:22

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

当用户访问我的网站时,他们会获得登录页面。成功登录后,他们可以注销,其他用户可以登录。但是,如果用户在登录时单击后退按钮,则会进入登录页面。此时,新用户无法再登录。我收到防伪令牌错误。

我尝试注销任何进入登录页面的用户。我尝试了其他注销方法。我什至尝试Session.Abandon();

帐户控制器:

// GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        EnsureLoggedOut();            
        ViewBag.ReturnUrl = returnUrl;
        // Store the originating URL so we can attach it to a form field
        var viewModel = new LoginViewModel { ReturnUrl = returnUrl };

        return View(viewModel);
    }

    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        ApplicationUser user = new ApplicationUser();
        try
        {
            user = DBcontext.Users.Where(u => u.Email.Equals(model.Email)).Single(); // where db is ApplicationDbContext instance

        }
        catch (InvalidOperationException)
        {
            // the user is not exist
            return View("The user does not exist.");
        }

        var result = await SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, shouldLockout: false);

        SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

    // POST: /Account/LogOff
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    { Session.Abandon();
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        return RedirectToAction("Index", "Home");
    }

    private ActionResult RedirectToLocal(string returnUrl)
    {
        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Home");
    }                

}

登录视图:

@model LoginViewModel
@{ViewBag.PageId = "extr-page";
ViewBag.PageClass = "animated fadeInDown";}

@section topright{<span id="extr-page-header-space"> <span class="hidden-mobile">Need an account?</span> <a href="@Url.Action("register", "account")" class="btn btn-danger">Create account</a> </span>
}

<div id="content" class="container">
<div class="row">
    @{ Html.RenderPartial("_LoginText"); }
    <div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
        <div class="well no-padding">
            <form action="@Url.Action("Login", "Account")" method="POST" id="login-form" class="smart-form client-form">
                <header>
                    Sign In
                </header>
                @Html.HiddenFor(m => m.ReturnUrl)
                @Html.AntiForgeryToken()
                @Html.ValidationBootstrap()
                <fieldset>
                    <section>
                        <label class="label">E-mail</label>
                        <label class="input">
                            <i class="icon-append fa fa-user"></i>
                            <input type="Email" name="Email" value="demo@email.com">
                            <b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i> Please enter email address/username</b>
                        </label>
                    </section>

                    <section>
                        <label class="label">Password</label>
                        <label class="input">
                            <i class="icon-append fa fa-lock"></i>
                            <input type="Password" name="Password" value="demo">
                            <b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i> Enter your password</b>
                        </label>
                        <div class="note">
                            <a href="@Url.Action("forgotpassword", "Account")"><i class="fa fa-frown-o"></i> Forgot password?</a>
                        </div>
                    </section>

                    <section>
                        <label class="checkbox">
                            <input type="checkbox" name="RememberMe" value="true" checked="checked">
                            <input type="hidden" name="RememberMe" value="false" />
                            <i></i>Stay signed in
                        </label>
                    </section>
                </fieldset>
                <footer>
                    <button type="submit" class="btn btn-primary">
                        Sign in
                    </button>
                </footer>
            </form>
        </div>
        @{ Html.RenderPartial("_SocialMedia"); }
    </div>
</div>

我希望当用户单击“后退”按钮并且他/她进入登录页面时,前一个用户被注销。

enter image description here

更新1: 明确地说,我不担心刚刚注销并单击“后退”按钮的用户。相反,当用户成功登录后,我的网站中断,然后单击“后退”按钮。它将它们带回“登录”页面,但是由于上述“防伪”错误,因此没有用户名或密码。

更新2: 我在IE中测试了代码,没有问题。经过进一步研究,当我按下“后退”按钮时,Chrome似乎正在保存身份验证Cookie。但是,当我正确注销时,cookie被破坏了。我认为当登录页面加载时,我正在调用LogOff方法,但它并未删除cookie。我将继续研究这个问题。也许有人对此有经验?

更新3:  我确实注意到,当我击退btn时,该cookie并未被删除。当我正确注销时,cookie被删除。当我不使用下面的Shoe的方法缓存页面时,在击回btn时cookie确实会被删除。但是,我仍然收到防伪令牌错误。有趣的是,我有一部分标头显示在登录页面上。该标头仅在用户通过身份验证时出现。还应该有一个备用菜单来弹出身份验证。但事实并非如此。我想知道是否有导致这两个问题的异步问题。

2 个答案:

答案 0 :(得分:1)

这可能是由于页面被缓存而导致的,并且无法针对登录用户验证为匿名用户生成的防伪令牌。

尝试在OutputCache ResponseCache上粘贴Login(核心为GET)属性,这将设置正确的标题以不缓存页面。

[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
public ActionResult Login(string returnUrl)
{
    ...
}

答案 1 :(得分:0)

我通过结合两件事解决了这个问题。

问题1: 我注意到当我击退btn并显示登录视图时,先前的用户cookie并未被破坏。这仅发生在chrome中,而不发生在IE中。这是通过我的[OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)] Login上的Get属性解决的(感谢@Shoe)。参见下面的代码。

登录:

// GET: /Account/Login
    [AllowAnonymous]
    [OutputCache(NoStore = true, Duration = 0, Location = OutputCacheLocation.None)]
    public ActionResult Login(string returnUrl)
    {
        EnsureLoggedOut();

        // Store the originating URL so we can attach it to a form field
        var viewModel = new LoginViewModel { ReturnUrl = returnUrl };

        return View(viewModel);
    } 

问题2: 第二个问题是,一旦显示了登录视图,我就调用了一种方法,用AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);Session.Abandon();来注销用户。直到我因为不明白的原因按下刷新按钮,才对用户进行身份验证。直到我添加第二步来清除主体,以确保通过向我的SecureLoggedOut方法中添加HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);来确保用户不保留任何身份验证。参见下面的代码。

EnsureLoggedOut方法:

private void EnsureLoggedOut()
    {
        if (AuthenticationManager.User.Identity.IsAuthenticated)
        {
            //SignOut the current user
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);
            Session.Abandon();

            // Second we clear the principal to ensure the user does not retain any authentication
            HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
        }
    }