Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating windows user credentials through native Java APIs

I need to store windows username and credentials to later run some process that requires these credentials.

When I am collecting these as inputs from user, I want to validate whether credentials are correct or not. Is there a native api in Java that can help me validate windows system credentials?

I was going through LoginContext class but looks like it can only be used for SSO purpose. One other suggestion I received was to try and start a process which requires these credentials and see if it works or fails. But this does not look the proper approach.

Please let me know if anyone has done this before or have any idea how to get it done.

Thanks, Piyush

like image 632
user1774433 Avatar asked Oct 25 '12 14:10

user1774433


1 Answers

By credentials, you mean the user's actual password? Then you can use LDAP to try to connect to a Windows Active Directory. See related question: Windows password Authentication with LDAP

A more elaborate way to do this is to use native windows calls, perhaps via the JNA platform: http://jna.java.net/javadoc/platform/com/sun/jna/platform/win32/package-summary.html

There's a project called 'waffle' that wrapped this in a more usefull library, see e.g. the logonUser function in https://github.com/dblock/waffle/blob/master/Source/JNA/waffle-jna/src/waffle/windows/auth/impl/WindowsAuthProviderImpl.java. This talks straight to the win32 advapi32.dll.

This will also allow you to do windows authentication for local users, without a domain.

EDIT: Full working code from OP

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.HANDLEByReference; 

HANDLEByReference phUser = new HANDLEByReference() 
if(! Advapi32.INSTANCE.LogonUser("administrator", InetAddress.getLocalHost().getHostName(),
    "password", WinBase.LOGON32_LOGON_NETWORK, WinBase.LOGON32_PROVIDER_DEFAULT, phUser)) 
{
  throw new LastErrorException(Kernel32.INSTANCE.GetLastError()); 
}
like image 106
GeertPt Avatar answered Nov 15 '22 16:11

GeertPt