What's wrong with my DLLImport LogonUser with String Marshaling? [FROM#]
For some odd reason, when I marshal the parameters LogonUser DLLImport
, I can no longer successfully login when using login type INTERACTIVE
, it works for login type NETWORK
.
This is my code:
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool LogonUser
(
[MarshalAs(UnmanagedType.LPStr)]
String lpszUsername,
[MarshalAs(UnmanagedType.LPStr)]
String lpszDomain,
[MarshalAs(UnmanagedType.LPStr)]
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr hToken
);
bResult = LogonUser(
"username",
".",
"password",
(int)LogonType.INTERACTIVE, // = 2
(int)LogonProvider.DEFAULT, // = 0
out hToken
);
Now when my call to LogonUser fails ( Logon Exception: Logon failure: unknown user name or bad password
) but if i remove [MarshalAs(UnmanagedType.LPStr)]
from DLLImport
it works fine also if i switch to LogonType.NETWORK
it works fine why is it different from INTERACTIVE
?
Unfortunately I need to keep it as I am using it with other features like LoadUserProfile
that it should be Marshalled (just the way I could get it to work, not displaying unknown Windows characters [squares]). Do I need to do funky string marshaling or something to get it to check correctly?
Any help would be greatly appreciated. Thank,
source to share
LogonUser uses LP T STR, not LPSTR, as parameters. You should just use the default string marshaling and it will work correctly.
See LogonUser and pinvoke.net declaration for the P / LogonUser call .
source to share
I had the same problem, but the reason was different. Then I realized that in the place where I work, we have to register our machines with a digital certificate instead of a user and password.
I forgot that we have this restriction on our domain.
So I need to use a different domain account instead of mine in order to test my application.
I don't know if this information will help, but they might be helpful for other people.
source to share