如何注销,以便在呈现页面时不知道用户已经过身份验证

本文关键字:不知道 用户 身份验证 经过 何注销 注销 | 更新日期: 2023-09-27 18:30:23

当我使用此控制器注销时:

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();
        return View();
    }
}

呈现的页面不知道我已注销,并且在剃须刀页面的一部分中,我向用户显示:

@if (Request.IsAuthenticated)
{
  <text>Welcome <strong>@Profile.GetPropertyValue("FullName")</strong> 
  @if (User.IsInRole("Administrator"))
  {
     @Html.ActionLink("(Administrator)", "Index", "Administration")
  } 
  [ @Html.ActionLink("Log Off", "Index", "LogOff") ]</text>
}
else
{
  @Html.ActionLink("Login", "Index", "Login")
}

这仍会显示用户名和管理员角色,就像他们仍然登录一样。我导航到的下一页是正确的。

如何注销,以便在呈现页面时不知道用户已经过身份验证

Dave Zych方法是一种首选的方法。但是,如果要像在原始问题中一样显示注销视图,则可以将 null 插入到当前线程的主体对象。

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();
        HttpContext.User = null;
        Thread.CurrentPrincipal = null;
        return View();
    }
}

不要返回视图,而是使用 RedirectToActionRedirectToRoute

public class LogOffController : Controller
{
    public ActionResult Index()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "MyController");
    }
}

这是因为HttpContext.User管道从身份验证 Cookie 读取值时 ASP.NET 设置的。当您执行FormsAuthentication.SignOut();时 - 您只需告诉浏览器删除身份验证cookie,但它对.NET当前用户一无所知。为了解决它,您有两种选择:

  • 将用户重定向到其他页面,以便您的请求再次通过管道和 .NET 知道用户是否经过身份验证。
  • 手动注销用户:

    var currentUser = new GenericPrincipal(new GenericIdentity(string.Empty), null);
    HttpContext.User = currentUser;
    Thread.CurrentPrincipal = currentUser;
    

    请注意,您不应将null分配为当前用户,因为在视图中您可能会遇到对User某些属性的调用,例如User.Identity.IsAuthenticated