Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have this code:

C#
public class Credenciales : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError=true)]
        private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
 
        [DllImport( "kernel32", SetLastError = true )]
        private static extern bool CloseHandle(IntPtr hObject);
 
        private IntPtr userHandle = IntPtr.Zero;
        private WindowsImpersonationContext impersonationContext;
 
        public Credenciales( string user, string domain, string password )
        {
                if ( ! string.IsNullOrEmpty( user ) )
                {
                        // Call LogonUser to get a token for the user
                        bool loggedOn = LogonUser( user, domain, password,
                                9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                                3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                                out userHandle );
                        if ( !loggedOn )
                                throw new Win32Exception( Marshal.GetLastWin32Error() );
 
                        // Begin impersonating the user
                        impersonationContext = WindowsIdentity.Impersonate( userHandle );
                }
        }
 
        public void Dispose()
        {
                if ( userHandle != IntPtr.Zero )
                        CloseHandle( userHandle );
                if ( impersonationContext != null )
                        impersonationContext.Undo();
        }
    }


And also I have installed BDE Administrator for Paradox Data Bases.

[Using the same PC] My problem is that when a user without administrator privileges account want to connect to DB, it's not working and I think it is because the user can't load DLLs and the administrator yes.

Is any solution for my problem? any different LogonUser maybe?

These is my other code:

C#
public int RZb()
        {
            xml = new XML();
 
            try
            {
                string myConnectionString = "Driver={Microsoft Paradox Driver (*.db )};" + "fil=Paradox 7.x;" + "driverid=538;" + "collatingsequence=ASCII;" + "dbq=" + xml.Recuperar("RelojBBDD") + ";" + "defaultdir=" + xml.Recuperar("RelojBBDD") + ";" + "paradoxnetpath=" + xml.Recuperar("RelojBBDDNetFiles") + ";" + "paradoxnetstyle=4.x;" + "paradoxusername=admin;" + "safetransactions=0;" + "threads=3;" + "uid=admin;" + "usercommitsync=Yes";
                OdbcConnection myConnection = new OdbcConnection();
                myConnection.ConnectionString = myConnectionString;
                myConnection.Open();
 
                //execute queries, etc
                OdbcCommand DbCommand = myConnection.CreateCommand();
                DbCommand.CommandText = "SELECT codigo, Nombre, DNI FROM Personal WHERE Baja=0 AND DNI LIKE '%" + ((Main)(this.Parent.Parent)).lblDNI.Text.Substring(0,8) + "%';";
                OdbcDataReader DbReader = DbCommand.ExecuteReader();
                OdbcDataAdapter da = new OdbcDataAdapter(DbCommand);
                DataSet dsRetrievedData = new DataSet();
                myConnection.Close();
                da.Fill(dsRetrievedData);
                DataRowCollection dra = dsRetrievedData.Tables["Table"].Rows;
                if (dra.Count == 0)
                {
                    myConnectionString = "Driver={Microsoft Paradox Driver (*.db )};" + "fil=Paradox 7.x;" + "driverid=538;" + "collatingsequence=ASCII;" + "dbq=" + xml.Recuperar("RelojUdaltzaingoBBDD") + ";" + "defaultdir=" + xml.Recuperar("RelojUdaltzaingoBBDD") + ";" + "paradoxnetpath=" + xml.Recuperar("RelojUdaltzaingoBBDDNetFiles") + ";" + "paradoxnetstyle=4.x;" + "paradoxusername=admin;" + "safetransactions=0;" + "threads=3;" + "uid=admin;" + "usercommitsync=Yes";
                    myConnection = new OdbcConnection();
                    myConnection.ConnectionString = myConnectionString;
                    myConnection.Open();
 
                    //execute queries, etc
                    DbCommand = myConnection.CreateCommand();
                    DbCommand.CommandText = "SELECT codigo, Nombre, DNI FROM Personal WHERE Baja=0 AND DNI LIKE '%" + ((Main)(this.Parent.Parent)).lblDNI.Text.Substring(0, 8) + "%';";
                    //DbCommand.CommandText = "SELECT codigo FROM Personal WHERE Nombre LIKE " + textBox4.Text + ";";
                    DbReader = DbCommand.ExecuteReader();
                    da = new OdbcDataAdapter(DbCommand);
                    dsRetrievedData = new DataSet();
                    myConnection.Close();
                    da.Fill(dsRetrievedData);
                    dra = dsRetrievedData.Tables["Table"].Rows;
                }
                foreach (DataRow dr in dra)
                {
                    RelojZb = int.Parse(dr["codigo"].ToString());
                }
                return RelojZb;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erroreak egon dira markajeekin edota beste erabiltzaile bat dago koltsulta egiten");
                return 0;
            }
        }
Posted

1 solution

Is it for local Users or in a Windows-Domain?

May you just use the administrator for executing some methods?

C#
private bool doSomeThingWithAdministrativePrivilegs()
        {
            IntPtr token;

            if (!NativeMethods.LogonUser(
                <$user>, //Administrator or User with administrativ privilegs
                <$domain>, //if no domain avalible set computername System.Environment.MachineName it was i think .ToString()...
                <$password>,
                NativeMethods.LogonType.NewCredentials,
                NativeMethods.LogonProvider.Default,
                out token))
            {
                throw new Win32Exception();
            }

            try
            {
                IntPtr tokenDuplicate;

                if (!NativeMethods.DuplicateToken(
                    token,
                    NativeMethods.SecurityImpersonationLevel.Impersonation,
                    out tokenDuplicate))
                {
                    throw new Win32Exception();
                }

                try
                {
                    using (WindowsImpersonationContext impersonationContext =
                        new WindowsIdentity(tokenDuplicate).Impersonate())
                    {
                        // DO the stuff privilegs needed in here...
                    }
                }
                finally
                {
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        if (!NativeMethods.CloseHandle(tokenDuplicate))
                        {
                            return false;
                            //throw new Win32Exception();
                        }
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    if (!NativeMethods.CloseHandle(token))
                    {
                        return false;
                        //throw new Win32Exception();
                    }
                }
            }
            return true;
        }


uncomment the win32exceptions and you can have a look if its really the privilegs that deny the access...
 
Share this answer
 
v2
Comments
kaiserssosse 12-Aug-11 3:31am    
Hi first of all thank you for your collaboration.

It's in Windows-Domain and it's installed BDE Administrator for Paradox Data Bases and this is the situation:

I have a folder in the server and It's only accessible with the user "Intranet" that has administrator privileges.

When the application is run for a user without administrator privileges, I impersonate a Intranet user to have access to that folder and everything run ok.

When I want to access to Paradox Data Base with a administrator user, there is no problem but with the normal user I have a error, and I think it's because with administrator account it's possible to load DLLs (I think it's IDAPI32.dll) dinamically and with normal user maybe don't.

So I want to activate the option for load DLLs with normal user with LogonUser method.

I hope everything is clear in my explanation.

Thank you very much.

P.D: I don't know what are you meaning with "NativeMethods", sorry.

P.D2: How can I call the method? with like I do before, with using?

P.D3: For more information about IDAPI32.dll. http://dll.paretologic.com/detail.php/idapi32
diialer 12-Aug-11 8:15am    
P.D: http://msdn.microsoft.com/en-us/library/system.security.principal.aspx
P.D2: Right-Click the dll. For testing add the User Everyone with full privilegs (better with the whole folder)

if this does not help use the method i postet before
export this to a method

if ( ! string.IsNullOrEmpty( user ) )
{
// Call LogonUser to get a token for the user
bool loggedOn = LogonUser( user, domain, password,
9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
out userHandle );
if ( !loggedOn )
throw new Win32Exception( Marshal.GetLastWin32Error() );

// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate( userHandle );
}

use method in doSomeThingWithAdministrativePrivilegs()
...
// DO the stuff privilegs needed in here...

put the method doSomeThingWithAdministrativePrivilegs() where your if ( ! string.IsNullOrEmpty( user ) ) ... was
you also can pass the user, password....
doSomeThingWithAdministrativePrivilegs(string user, string domain, string password)

you have to change the following lines in the method:
<$user>, //Administrator or User with administrativ privilegs
<$domain>, //if no domain avalible set computername System.Environment.MachineName it was i think .ToString()...
<$password>,
this is for example the domain administrator or a user who has administrativ privilegs in domain...

AND to use local administrator if possible:
Create manifest file for main application and add

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestversion="1.0">
<assemblyidentity version="1.0.0.0"
="" processorarchitecture="X86" name="someExecName" type="win32">
<description>Your Program Description
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security>
<requestedprivileges>
<requestedexecutionlevel level="requireAdministrator">


</trustInfo>
kaiserssosse 22-Aug-11 3:03am    
Thanks for the reply.

I think the problem is the computer and the accounts, because with an old account it doesn't work but if we copy the privileges of the account to a new account it works fine, so I don't know which is the problem with all of this.

It can be because the accounts are old and when it was created it was done with a winNT version and not with the winXP SP3, or is a problem of cache files in the computer...

In some computers works perfectly, in others only works with some users, normally old accounts. This is a mysterious.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900