Search code examples
javawindowswinapijna

LogonUser with JNA leads to "unknown user name or bad password"


I try to implement a functionality to execute some application with certain credentials. For that I check if a logon with the credentials is possible.

import com.sun.jna.LastErrorException;
import com.sun.jna.platform.win32.Advapi32;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class TestHarness {

    public static void main(String[] args) throws UnknownHostException {

        WinNT.HANDLEByReference phUser = new WinNT.HANDLEByReference();
        System.out.println(InetAddress.getLocalHost().getHostName());
        if (!Advapi32.INSTANCE.LogonUser("de313e", ".",
                "password", WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser)) {
            throw new LastErrorException(Kernel32.INSTANCE.GetLastError());
        }
    }
}

This unfortunately gives me

com.sun.jna.LastErrorException: GetLastError() returned 1326

The provided username is my current username. Why does this not work?

I am running it on Windows 10. My password contains some special characters like ! and &. The user is named in:

enter image description here


Solution

  • The documentation for LogonUser states for the parameter lpszDomain:

    A pointer to a null-terminated string that specifies the name of the domain or server whose account database contains the lpszUsername account. If this parameter is NULL, the user name must be specified in UPN format. If this parameter is ".", the function validates the account by using only the local account database.

    Since you are using "." you are only validating against the local user database. This would work for the sysadmin account on the local computer (NB3DE2730054). However, you are attempting to validate a domain user, de313e so you must specify the domain, MASTDOM.

    As an alternative you could set the domain to null and include the domain with the user: de313e@MASTDOM. Or, as you've noted in the comments, if you use the logonType LOGON32_LOGON_NEW_CREDENTIALS and logonProvider LOGON32_PROVIDER_WINNT50 the "." will work.