-
April 16th, 2003, 04:18 AM
#1
Logonuser
Can somebody tell me how to use LogonUser API with C#?
I tried using the following code, but it gave an error.
Code:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
public class Class1
{
[DllImport("C:\\WINNT\\System32\\advapi32.dll")]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, out int phToken);
[DllImport("C:\\WINNT\\System32\\Kernel32.dll")]
public static extern int GetLastError();
public static void Main(string[] args)
{
// The Windows NT user token.
int token1;
// Get the user token for the specified user, machine, and password using the unmanaged LogonUser method.
bool loggedOn = LogonUser(
// User name.
"Username",
// Computer name.
"Domain",
// Password.
"Password",
// Logon type = LOGON32_LOGON_NETWORK.
2,
// Logon provider = LOGON32_PROVIDER_DEFAULT.
0,
// The user token for the specified user is returned here.
out token1);
Console.WriteLine("LogonUser called");
// Call GetLastError to try to determine why logon failed if it did not succeed.
int ret = GetLastError();
Console.WriteLine("LogonUser Success? " + loggedOn);
Console.WriteLine("NT Token Value: " + token1);
if (ret != 0) Console.WriteLine("Error code (126 == \"Specified module could not be found\"): " + ret);
//Starting impersonation here:
Console.WriteLine("\n\nBefore impersonation:\n");
WindowsIdentity mWI1 = WindowsIdentity.GetCurrent();
Console.WriteLine(mWI1.Name);
Console.WriteLine(mWI1.Token);
IntPtr token2 = new IntPtr(token1);
Console.WriteLine("\n\nNew identity created:\n");
WindowsIdentity mWI2 = new WindowsIdentity(token2);
Console.WriteLine(mWI2.Name);
Console.WriteLine(mWI2.Token);
// Impersonate the user.
WindowsImpersonationContext mWIC = mWI2.Impersonate();
Console.WriteLine("\n\nAfter impersonation:\n");
WindowsIdentity mWI3 = WindowsIdentity.GetCurrent();
Console.WriteLine(mWI3.Name);
Console.WriteLine(mWI3.Token);
// Revert to previous identity.
mWIC.Undo();
Console.WriteLine("\n\nAfter impersonation is reverted:\n");
WindowsIdentity mWI4 = WindowsIdentity.GetCurrent();
Console.WriteLine(mWI4.Name);
Console.WriteLine(mWI4.Token);
}
}
Thanks in advance.
Muthu
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|