在ASP.MVC中以不同用户身份登录不会更改用户标识

本文关键字:登录 用户标识 身份 MVC ASP 用户 | 更新日期: 2023-09-27 18:29:18

我正在使用Windows身份验证开发一个MVC web应用程序。其目的是允许在打开页面时自动登录,但允许按需以不同用户身份签名。我正在尝试使用这里的代码';以其他用户身份登录';MVC 4 Windows身份验证和此处http://www.roelvanlisdonk.nl/?p=825但他们都不适合我。

我已经最大限度地简化了这个案例,所以它看起来如下:

public string Logout()
{
    AuthenticationAttempts = AuthenticationAttempts + 1;
    if (AuthenticationAttempts == 1)
    {
        this.Send401();
    }
    var domain = User.Identity.Name.Split('''')[0];
    var user = User.Identity.Name.Split('''')[1];
    return string.Format("Domain: {0}<br>User: {1}", domain, user);
}
/// <summary>
/// Send a 401 response
/// </summary>
public void Send401()
{
    // Create a 401 response, the browser will show the log-in dialogbox, asking the user to supply new credentials, 
    // if browser is not set to "automaticaly sign in with current credentials"
    Response.Buffer = true;
    Response.StatusCode = 401;
    Response.StatusDescription = "Unauthorized";
    // A authentication header must be supplied. This header can be changed to Negotiate when using keberos authentication
    Response.AddHeader("WWW-Authenticate", "NTLM");
    // Send the 401 response
    Response.End();
}
private int _authenticationAttempts = 0;
public int AuthenticationAttempts
{
    get
    {
        if (!string.IsNullOrEmpty(string.Format("{0}", Session["AuthenticationAttempts"])))
        {
            int.TryParse(Session["AuthenticationAttempts"].ToString(), out _authenticationAttempts);
        }
        return _authenticationAttempts;
    }
    set
    {
        _authenticationAttempts = value;
        Session["AuthenticationAttempts"] = _authenticationAttempts;
    }
}

当我第一次调用Logout操作方法时,我得到了登录窗口,但当我单击"确定"时,User.Identity仍然是原来的样子。

编辑:

我发现

Request.ServerVariables["LOGON_USER"]

存储新登录的用户标识,但为什么user.identity没有更改?

在ASP.MVC中以不同用户身份登录不会更改用户标识

步骤1:打开Web.config文件并进行以下修改:

<!—
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
-->
<authentication mode="Windows" />

步骤2:默认情况下,MVC应用程序使用表单身份验证和简单成员身份,因此您需要将其设置为"false"才能运行Windows身份验证。

<appSettings>
  <add key="webpages:Version" value="2.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="PreserveLoginUrl" value="true" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="autoFormsAuthentication" value="false" />
  <add key="enableSimpleMembership" value="false"/>
</appSettings>

步骤3:在解决方案资源管理器中选择项目名称,然后在属性资源管理器上单击以启用Windows身份验证。

步骤4:如果您希望在开发服务器上为经过身份验证的用户提供完整的网站,则可以在属性资源管理器中禁用匿名身份验证。

参考