User impersonation with asp.net forms authentication

I wrote a small ASP.NET 3.5 application so that users can update their selected account attributes on their own.

Everything works fine when I use Basic Authentication, but since the dialog box presented is less than ideal, I would like to use authentication in formats to give users more detailed login instructions.

My problem is that in order for the user to update their account information, I need the application to impersonate the update actions.

I browsed the Internet, trying to find a solution to my problem, but nothing fits or doesn't work. I tried installing web.config:

<identity impersonate="true">

but this does not seem to work. I also have C # code using the WindowsImpersonationContext class , but still no luck.

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

I also tried using the LogonUser method to create a user token and authenticate in this way, and it also does not work.

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

I just can't help but think that I am missing something incredibly simple ...

+3
source share
1 answer

Do you have Windows authentication enabled and anonymous authentication disabled in IIS?

ASP.NET, : • IIS, IUSR_machinename.
• IIS, .

+1

Source: https://habr.com/ru/post/1762671/


All Articles