c# - 使用 asp.net 表单例份验证的用户模拟

标签 c# asp.net active-directory forms-authentication impersonation

我编写了一个小型 ASP.NET 3.5 应用程序,允许用户自行更新选定的帐户属性。

当我使用基本身份验证时一切正常,但由于显示的对话框不太理想,我想使用表单例份验证为用户提供更多有关如何登录的说明。

我的问题是,为了让用户更新他们的帐户信息,我必须让应用程序模拟他们进行更新操作。

我在互联网上搜索过,试图找到解决我的问题的方法,但没有一个适合或有效。我已尝试设置 web.config:

<identity impersonate="true">

但这似乎行不通。 我也有使用 WindowsImpersonationContext 类的 C# 代码,但还是不行。

protected void titleTextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    string fieldTitle = "job title";
    string fieldName = "title";

    if (userDirectoryEntry == null)
        CaptureUserIdentity();
    try
    {
        WindowsImpersonationContext impersonationContext = userWindowsIdentity.Impersonate();
        if (String.IsNullOrEmpty(tb.Text))
            userDirectoryEntry.Properties[fieldName].Clear();
        else
            userDirectoryEntry.InvokeSet(fieldName, tb.Text);
        userDirectoryEntry.CommitChanges();
        impersonationContext.Undo();
        PostBackMessages.Add(fieldTitle, "");
    }
    catch (Exception E)
    {
        PostBackMessages.Add(fieldTitle, E.Message);
    }
}

我还尝试使用 LogonUser 方法创建用户 token 并以这种方式后端验证,但它也不起作用。

IntPtr token = IntPtr.Zero;
bool result = LogonUser(userName, domainName, passwordTB.Text, LogonSessionType.Network, LogonProvider.Default, out token);

if (result)
{
     WindowsPrincipal wp = new WindowsPrincipal(new WindowsIdentity(token));
     System.Threading.Thread.CurrentPrincipal = wp;
     HttpContext.Current.User = wp;
     if (Request.QueryString["ReturnUrl"] != null)
     {
          FormsAuthentication.RedirectFromLoginPage(usernameTB.Text, false);
     }
     else
     {
          FormsAuthentication.SetAuthCookie(usernameTB.Text, false);
     }
}

我只是忍不住想我错过了一些非常简单的东西......

最佳答案

有没有enabled Windows Authentication并在 IIS 中禁用匿名身份验证?

如果在 ASP.NET 应用程序中启用模拟,则:
• 如果在 IIS 中启用了匿名访问,则使用 IUSR_machinename 帐户发出请求。
• 如果在 IIS 中禁用了匿名访问,则使用经过身份验证的用户的帐户发出请求。

关于c# - 使用 asp.net 表单例份验证的用户模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3619160/

相关文章:

c# - 反序列化抽象类

c# - 如何使用 xUnit 进行调试?

c# - 如何根据第一个ListView中选择的值显示第二个ListView?

azure - Active Directory 上授予同意失败并出现错误

active-directory - 连接到端口 636 时出现 LDAP 连接错误 ("The server is not operational.")

c# - .NET/CSS Foreach 复选框独立样式

c# - 服务器从客户端接收消息,如何在Active Window中将消息转换为击键?

c# - GridView - SqlDataSource 中的客户端 "WHERE"子句?

c# - 无法将 NULL 值插入列 'module_desc'

powershell - 以多个用户身份运行Powershell脚本