为什么即使注销后User.Identity.IsAuthenticated始终为true

时间:2018-12-31 16:02:24

标签: asp.net-mvc asp.net-core-2.1

我正在研究AspnetCore 2.1 MVC应用程序,它具有Windows集成身份验证。我已经使用await HttpContext.SignInAsync()实现了登录和注销功能。它是基于cookie的身份验证,该cookie在我提供的指定时间后过期。

我的问题是用户注销后必须从导航栏隐藏注销。但是在_layout.cshtml中,即使用户单击注销,@ User.Identity.Is仍始终为true。有什么帮助吗?下面是我正在使用的代码

<div class="navbar-collapse collapse">
            @if(User.Identity.IsAuthenticated)
            {
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="InitiatedCases" asp-action="Index">Initiated Cases</a></li>
                    <li><a asp-area="" asp-controller="SubmittedCases" asp-action="Index">Submitted Cases</a></li>
                    <li><a asp-area="" asp-controller="UserAccessLogs" asp-action="Index">User Access Log</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right">
                    <li><a asp-controller="Account" asp-action="Logout">Logout</a></li>
                    <li><p class="nav navbar-text navbar-right">@User.Identity.Name!</p></li>

                </ul>
            }
            else
            {
                <p></p>

            }

            </div>

下面是登录功能

var usrRole = _dbContext.UserAccess.Where(r => r.UserId == loginUser.UserId).FirstOrDefault();
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);

identity.AddClaim(new Claim(ClaimTypes.Name, loginUser.UserId.ToString()));
identity.AddClaim(new Claim("DisplayName", loginUser.UserId));

if (usrRole != null)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, usrRole.UserRole.ToString()));
}

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(identity),
    new AuthenticationProperties
    {
        IsPersistent = true,
        IssuedUtc = DateTime.Now,
        ExpiresUtc = DateTime.Now.AddMinutes(_iconfiguration.GetValue<double>("Session:TimeOutInMinutes")),
        AllowRefresh = false
    });

1 个答案:

答案 0 :(得分:0)

我认为您可能正在使用Windows集成身份验证-尽管我不确定。

浏览器使用Windows集成身份验证-这意味着它将自动使用用户的Windows凭据登录用户-

这就是为什么IsAuthenticated始终为真。

其他想法: 我没有尝试下面的代码,但是有一个叫做IISServerOptions的东西。 您可以尝试让他们检查是否适合您。

services.Configure<IISServerOptions>(options => 
{
    options.AutomaticAuthentication = false;
});
相关问题