【问题标题】:User impersonation with asp.net forms authentication使用 asp.net 表单身份验证的用户模拟
【发布时间】:2011-04-06 20:35:24
【问题描述】:

我编写了一个小型 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);
     }
}

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 为了使表单身份验证工作,我必须启用匿名身份验证。在尝试通过 IIS 直接模拟时,由于委派问题,我无法使用 Windows 身份验证,并且基本身份验证(虽然它有效)很笨重,而且对用户不友好。
    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2014-09-08
    相关资源
    最近更新 更多