用户模拟asp.net表单身份验证

时间:2010-09-01 14:32:11

标签: 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 方法创建用户令牌并以这种方式后端验证,但它也不起作用。

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);
     }
}

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

1 个答案:

答案 0 :(得分:1)

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

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