如何获取Request.IsAuthenticated返回false?

时间:2015-12-03 11:30:26

标签: asp.net asp.net-mvc owin katana asp.net-mvc-5.2

我想签署一个用户,并且Request.IsAuthenticated属性返回false。

我没有使用FormsAuthentication,而是使用Katana中提供的默认CookieAuthentication。

当用户的会话过期时,我想签下他,所以我有一个这样的动作过滤器:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var session = filterContext.HttpContext.Session;

    if (session.IsNewSession || session["UserId"] == null)
    {
        if (filterContext.RequestContext.HttpContext.Request.IsAuthenticated)
        {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult { Data = BusinessObjects.Constants.SessionExpiredJsonResult };
            }
            else
            {
                var authenticationManager = filterContext.HttpContext.GetOwinContext().Authentication;

                if (authenticationManager != null)
                {
                    authenticationManager.SignOut();

                    Trace.TraceInformation(filterContext.HttpContext.User == null ? "User is null" : "User is not null");
                    Trace.TraceInformation(filterContext.HttpContext.User.Identity == null ? "User.Identity is null" : "User.Identity is not null");
                    Trace.TraceInformation(filterContext.RequestContext.HttpContext.Request.IsAuthenticated.ToString());
                }

                filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/SessionExpired.cshtml" };
            }
        }
    }

    base.OnActionExecuting(filterContext);
}

SessionExpired 视图很好地加载,但它有一个部分视图呈现,它有以下代码:

@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink((string)(Session["FullName"] ?? User.Identity.Name), "Index", controllerName })
        </li>

        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        <li>
            @Html.ActionLink("Sign up", "Signup", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })
        </li>
    </ul>

}

执行此部分视图时,即使HttpSessionStateHttpSessionBase对象为null,Request.IsAuthenticated属性也会返回true。因此,我确实看到用户仍然登录,即使他的会话已经过期,我甚至先前已经调用了authenticationManager.SignOut()

如何让用户的身份信息消失,从而让Request.IsAuthenticated属性返回false?

0 个答案:

没有答案