locked
About Impersonation RRS feed

  • Question

  • User-745611520 posted

    Hi All,

            I want to upload file into network shared location from Machine 1 to Machine 2.

            I' m getting error message when saving file into network location as "Logon failure : Unknown username or bad password".

            Suppose when i am implementing Impersonation if both Machine 1 and Machine 2 needs to have same username and password ??

            Please advice.

    Thanks,

    Selvakumar.S

    Thursday, May 15, 2014 6:59 AM

Answers

  • User-1818759697 posted

    Hi,

    By default, an ASP.NET application runs under the security   context of an ASPNET user account. The ASP.NET application accesses the remote   security-enhanced resource by using the ASPNET user account when the following   conditions are true:   

    • When the impersonation feature is not turned on for the ASP.NET application
    • When the authentication method in Microsoft Internet Information Services (IIS) is set to anonymous access

    However, the ASPNET user account may not have permissions to   access the remote security-enhanced resource.

    For detailed information, you could refer to:

    http://support.microsoft.com/kb/842789

    http://forums.asp.net/t/1253467.aspx?Logon+failure+unknown+user+name+or+bad+password+

    http://support.microsoft.com/kb/306158

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 16, 2014 3:33 AM
  • User-745611520 posted

     

    CAUSE:

                When access network shared file (i.e. \\192.168.1.120\InputFile\Docu.txt) from asp.net or c# console application then IO exception caught as “Logon failed: unknown username or bad password.”

                    In perform SQL bulk operation getting error message as “Cannot bulk load because the file "\\192.168.1.120\InputFile\Docu.txt" could not be opened. Operating system error code 1326(Logon failure: unknown user name or bad password.)” 

     

    SOLUTION:

     

    Solution (First Ensure you have identical user account is present in local and remote computer, if not present follow the below steps to create identical user account)

    We know for a fact that we need to impersonate because the aspnet_wp account would not have access to the folder and if we do not have a network user to access the resource follow the simple steps below:

     

    • Create a local user account  in web server say UserX with password Password123
    • Create a local user account in File server with same name as above and same password UserX and Password123
    • If you are using windows xp or windows .net server 2003 you don’t need do anything
    • If you have Windows 2000 go to Start menu à local security policy à local policies à and browse to “User Rights assignment” and locate “Act as part of Operating System” policy. Double click and add “aspnet_wp” account

     

    • Restart IIS service

     

            You need to set permission for impersonated user for full control on C:\winnt\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files so that the stream read from client as temporary stored in this folder till it is transferred to the Virtual Folder

     

    Solution (For Asp.Net):

     

    1. Add impersonate tab in Web.config file as

     

    <system.web>

                  <identity impersonate="true" userName="identical username" password="identical password"/>

    </system.web>

    Note: common user with credential need in both local machine and remote machine

     

    (OR)

    Add new class and paste the below code and modify the block (// Here Your code block to access the file)

     

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Linq;

    using System.Runtime.ConstrainedExecution;

    using System.Runtime.InteropServices;

    using System.Security;

    using System.Security.Permissions;

    using System.Security.Principal;

    using System.Text;

    using System.Threading.Tasks;

    using System.Xml.XPath;

    using log4net;

    using Microsoft.Win32.SafeHandles;

     

    namespace MBADI

    {

        class Impersonate:IDisposable

        {

            protected static readonly ILog loger = LogManager.GetLogger(typeof(CommonFunctions));

            public static string lProgramName = "Impersonate";

     

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,

                int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

     

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

            public extern static bool CloseHandle(IntPtr handle);

     

            // Test harness.

            // If you incorporate this code into a DLL, be sure to demand FullTrust.

            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

            public void fCheckInputFileIsAccessible(string path)

            {

                SafeTokenHandle safeTokenHandle;

                try

                {

                    const int LOGON32_PROVIDER_DEFAULT = 0;

                    //This parameter causes LogonUser to create a primary token.

                    const int LOGON32_LOGON_INTERACTIVE = 2;

                    IntPtr tokenHandle = IntPtr.Zero;

                    bool returnValue = LogonUser(ImpersonateUserName, ImpersonateDomainName, ImpersonatePassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

     

                    if (false == returnValue)

                    {

                        int ret = Marshal.GetLastWin32Error();

                        Console.WriteLine("LogonUser failed with error code : {0}", ret);

                        throw new System.ComponentModel.Win32Exception(ret);

                    }

                    using (safeTokenHandle)

                    {

                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))

                        {

                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())

                            {

    // Here Your code block to access the file

                            }

                        }

                    }

                }

                catch (FileNotFoundException ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

                catch (Exception ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

            }

     

     

            public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid

            {

                private SafeTokenHandle()

                    : base(true)

                {

                }

     

                [DllImport("kernel32.dll")]

                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

                [SuppressUnmanagedCodeSecurity]

                [return: MarshalAs(UnmanagedType.Bool)]

                private static extern bool CloseHandle(IntPtr handle);

     

                protected override bool ReleaseHandle()

                {

                    return CloseHandle(handle);

                }

            }

     

            public void Dispose()

            {

            }

        }

    }

     

    Solution (For C# Console application):

     

    Add new class and paste the below code and modify the block (// Here Your code block to access the file)

     

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Linq;

    using System.Runtime.ConstrainedExecution;

    using System.Runtime.InteropServices;

    using System.Security;

    using System.Security.Permissions;

    using System.Security.Principal;

    using System.Text;

    using System.Threading.Tasks;

    using System.Xml.XPath;

    using log4net;

    using Microsoft.Win32.SafeHandles;

     

    namespace MBADI

    {

        class Impersonate:IDisposable

        {

            protected static readonly ILog loger = LogManager.GetLogger(typeof(CommonFunctions));

            public static string lProgramName = "Impersonate";

     

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,

                int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

     

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

            public extern static bool CloseHandle(IntPtr handle);

     

            // Test harness.

            // If you incorporate this code into a DLL, be sure to demand FullTrust.

            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

            public void fCheckInputFileIsAccessible(string path)

            {

                SafeTokenHandle safeTokenHandle;

                try

                {

                    const int LOGON32_PROVIDER_DEFAULT = 0;

                    //This parameter causes LogonUser to create a primary token.

                    const int LOGON32_LOGON_INTERACTIVE = 2;

                    IntPtr tokenHandle = IntPtr.Zero;

                    bool returnValue = LogonUser(ImpersonateUserName, ImpersonateDomainName, ImpersonatePassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

     

                    if (false == returnValue)

                    {

                        int ret = Marshal.GetLastWin32Error();

                        Console.WriteLine("LogonUser failed with error code : {0}", ret);

                        throw new System.ComponentModel.Win32Exception(ret);

                    }

                    using (safeTokenHandle)

                    {

                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))

                        {

                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())

                            {

    // Here Your code block to access the file

                            }

                        }

                    }

                }

                catch (FileNotFoundException ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

                catch (Exception ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

            }

     

     

            public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid

            {

                private SafeTokenHandle()

                    : base(true)

                {

                }

     

                [DllImport("kernel32.dll")]

                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

                [SuppressUnmanagedCodeSecurity]

                [return: MarshalAs(UnmanagedType.Bool)]

                private static extern bool CloseHandle(IntPtr handle);

     

                protected override bool ReleaseHandle()

                {

                    return CloseHandle(handle);

                }

            }

     

            public void Dispose()

            {

            }

        }

    }

     

    Solution (For SQL Server):

     

    1. Go to Run command à Type Services.msc and press enter à SQL service for your instance

    1. Right click on SQL server service à go to properties à move to Log on tab

    1. Choose this account and Provide Identical username and password
    2. Stop the SQL service
    3. Restart the SQL service
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 16, 2014 10:34 AM

All replies

  • User-1818759697 posted

    Hi,

    By default, an ASP.NET application runs under the security   context of an ASPNET user account. The ASP.NET application accesses the remote   security-enhanced resource by using the ASPNET user account when the following   conditions are true:   

    • When the impersonation feature is not turned on for the ASP.NET application
    • When the authentication method in Microsoft Internet Information Services (IIS) is set to anonymous access

    However, the ASPNET user account may not have permissions to   access the remote security-enhanced resource.

    For detailed information, you could refer to:

    http://support.microsoft.com/kb/842789

    http://forums.asp.net/t/1253467.aspx?Logon+failure+unknown+user+name+or+bad+password+

    http://support.microsoft.com/kb/306158

    Regards

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 16, 2014 3:33 AM
  • User-745611520 posted

     

    CAUSE:

                When access network shared file (i.e. \\192.168.1.120\InputFile\Docu.txt) from asp.net or c# console application then IO exception caught as “Logon failed: unknown username or bad password.”

                    In perform SQL bulk operation getting error message as “Cannot bulk load because the file "\\192.168.1.120\InputFile\Docu.txt" could not be opened. Operating system error code 1326(Logon failure: unknown user name or bad password.)” 

     

    SOLUTION:

     

    Solution (First Ensure you have identical user account is present in local and remote computer, if not present follow the below steps to create identical user account)

    We know for a fact that we need to impersonate because the aspnet_wp account would not have access to the folder and if we do not have a network user to access the resource follow the simple steps below:

     

    • Create a local user account  in web server say UserX with password Password123
    • Create a local user account in File server with same name as above and same password UserX and Password123
    • If you are using windows xp or windows .net server 2003 you don’t need do anything
    • If you have Windows 2000 go to Start menu à local security policy à local policies à and browse to “User Rights assignment” and locate “Act as part of Operating System” policy. Double click and add “aspnet_wp” account

     

    • Restart IIS service

     

            You need to set permission for impersonated user for full control on C:\winnt\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files so that the stream read from client as temporary stored in this folder till it is transferred to the Virtual Folder

     

    Solution (For Asp.Net):

     

    1. Add impersonate tab in Web.config file as

     

    <system.web>

                  <identity impersonate="true" userName="identical username" password="identical password"/>

    </system.web>

    Note: common user with credential need in both local machine and remote machine

     

    (OR)

    Add new class and paste the below code and modify the block (// Here Your code block to access the file)

     

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Linq;

    using System.Runtime.ConstrainedExecution;

    using System.Runtime.InteropServices;

    using System.Security;

    using System.Security.Permissions;

    using System.Security.Principal;

    using System.Text;

    using System.Threading.Tasks;

    using System.Xml.XPath;

    using log4net;

    using Microsoft.Win32.SafeHandles;

     

    namespace MBADI

    {

        class Impersonate:IDisposable

        {

            protected static readonly ILog loger = LogManager.GetLogger(typeof(CommonFunctions));

            public static string lProgramName = "Impersonate";

     

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,

                int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

     

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

            public extern static bool CloseHandle(IntPtr handle);

     

            // Test harness.

            // If you incorporate this code into a DLL, be sure to demand FullTrust.

            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

            public void fCheckInputFileIsAccessible(string path)

            {

                SafeTokenHandle safeTokenHandle;

                try

                {

                    const int LOGON32_PROVIDER_DEFAULT = 0;

                    //This parameter causes LogonUser to create a primary token.

                    const int LOGON32_LOGON_INTERACTIVE = 2;

                    IntPtr tokenHandle = IntPtr.Zero;

                    bool returnValue = LogonUser(ImpersonateUserName, ImpersonateDomainName, ImpersonatePassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

     

                    if (false == returnValue)

                    {

                        int ret = Marshal.GetLastWin32Error();

                        Console.WriteLine("LogonUser failed with error code : {0}", ret);

                        throw new System.ComponentModel.Win32Exception(ret);

                    }

                    using (safeTokenHandle)

                    {

                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))

                        {

                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())

                            {

    // Here Your code block to access the file

                            }

                        }

                    }

                }

                catch (FileNotFoundException ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

                catch (Exception ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

            }

     

     

            public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid

            {

                private SafeTokenHandle()

                    : base(true)

                {

                }

     

                [DllImport("kernel32.dll")]

                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

                [SuppressUnmanagedCodeSecurity]

                [return: MarshalAs(UnmanagedType.Bool)]

                private static extern bool CloseHandle(IntPtr handle);

     

                protected override bool ReleaseHandle()

                {

                    return CloseHandle(handle);

                }

            }

     

            public void Dispose()

            {

            }

        }

    }

     

    Solution (For C# Console application):

     

    Add new class and paste the below code and modify the block (// Here Your code block to access the file)

     

    using System;

    using System.Collections.Generic;

    using System.IO;

    using System.Linq;

    using System.Runtime.ConstrainedExecution;

    using System.Runtime.InteropServices;

    using System.Security;

    using System.Security.Permissions;

    using System.Security.Principal;

    using System.Text;

    using System.Threading.Tasks;

    using System.Xml.XPath;

    using log4net;

    using Microsoft.Win32.SafeHandles;

     

    namespace MBADI

    {

        class Impersonate:IDisposable

        {

            protected static readonly ILog loger = LogManager.GetLogger(typeof(CommonFunctions));

            public static string lProgramName = "Impersonate";

     

            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

            public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,

                int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

     

            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]

            public extern static bool CloseHandle(IntPtr handle);

     

            // Test harness.

            // If you incorporate this code into a DLL, be sure to demand FullTrust.

            [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]

            public void fCheckInputFileIsAccessible(string path)

            {

                SafeTokenHandle safeTokenHandle;

                try

                {

                    const int LOGON32_PROVIDER_DEFAULT = 0;

                    //This parameter causes LogonUser to create a primary token.

                    const int LOGON32_LOGON_INTERACTIVE = 2;

                    IntPtr tokenHandle = IntPtr.Zero;

                    bool returnValue = LogonUser(ImpersonateUserName, ImpersonateDomainName, ImpersonatePassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

     

                    if (false == returnValue)

                    {

                        int ret = Marshal.GetLastWin32Error();

                        Console.WriteLine("LogonUser failed with error code : {0}", ret);

                        throw new System.ComponentModel.Win32Exception(ret);

                    }

                    using (safeTokenHandle)

                    {

                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))

                        {

                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())

                            {

    // Here Your code block to access the file

                            }

                        }

                    }

                }

                catch (FileNotFoundException ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

                catch (Exception ex)

                {

                    loger.Error(lProgramName + " - Error in fCheckInputFileIsAccessible : " + ex.Message);

                    throw;

                }

            }

     

     

            public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid

            {

                private SafeTokenHandle()

                    : base(true)

                {

                }

     

                [DllImport("kernel32.dll")]

                [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]

                [SuppressUnmanagedCodeSecurity]

                [return: MarshalAs(UnmanagedType.Bool)]

                private static extern bool CloseHandle(IntPtr handle);

     

                protected override bool ReleaseHandle()

                {

                    return CloseHandle(handle);

                }

            }

     

            public void Dispose()

            {

            }

        }

    }

     

    Solution (For SQL Server):

     

    1. Go to Run command à Type Services.msc and press enter à SQL service for your instance

    1. Right click on SQL server service à go to properties à move to Log on tab

    1. Choose this account and Provide Identical username and password
    2. Stop the SQL service
    3. Restart the SQL service
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, May 16, 2014 10:34 AM