简体   繁体   中英

C# Win Form login failure

I'm trying to upload file from my PC to remote server with win form and I get the following error: Logon failure: unknown user name or bad password. On my computer I'm using my domain user and to upload the file local user of the remote server

I founded, that I need to impersonate my user but I still didn't get how I impersonate NetworkCredential.

This my code:

if (tbUsername.Text != string.Empty && tbPassword.Text != string.Empty && userSelectedFilePath != string.Empty)
{
    try
    {
        using (WindowsIdentity.GetCurrent().Impersonate())
        {
            WebClient client = new WebClient();

            NetworkCredential nc = new NetworkCredential("\\\\" + targetServer.Host + "\\" + tbUsername.ToString(), tbPassword.ToString());

            client.Credentials = nc;
            client.UploadFile(targetServer, filepath);
            MessageBox.Show("the file was successfully uploaded", "information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
else
{
    MessageBox.Show("One of the fields is empty", "Fields Empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Do following steps:

Open 'Control panel'

Select 'Administrative Tools'

Open 'Local security policy'

On the left pane navigate to 'Security Settings' => 'Local policies' => 'Security Options'

On the right pane find 'Network access: Sharing and security model for local accounts'

Double-click on it in order to change

Set it to 'Classic - Local users authenticate as themselves'

I have rewritten my code section and it works fine now. It looks now like this:

                    IntPtr admin_token = default(IntPtr);
                    WindowsIdentity wid_current = WindowsIdentity.GetCurrent();
                    WindowsIdentity wid_admin = null;
                    WindowsImpersonationContext wic = null;

                    if ((LogonUser(tbUsername.Text, targetServer.Host, tbPassword.Text, 9, 0, ref admin_token)) != 0 || (LogonUser(tbUsername2.Text, targetServer.Host, tbPassword2.Text, 9, 0, ref admin_token)) != 0)
                    {
                        wid_admin = new WindowsIdentity(admin_token);
                        wic = wid_admin.Impersonate();
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM