Validating windows user credentials through native Java APIs

人盡茶涼 提交于 2019-12-23 07:38:08

问题


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


回答1:


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()); 
}


来源:https://stackoverflow.com/questions/13070587/validating-windows-user-credentials-through-native-java-apis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!