如何在Java中对本机操作系统进行身份验证而不使用JNI?

His*_*His 3 java authentication

我的Java RCP应用程序在启动时提示用户输入用户名和密码.如何在不使用JNI移植某些C库的情况下使用这些凭据对本机操作系统进行身份验证?谢谢!

PS.如果可能,不使用第三方库的纯Java实现将是非常可取的.

Law*_*Dol 8

AFAIK,如果不以某种方式涉及Java的本机扩展,这是不可能的 - 没有Java API.

你可以看看JNA项目.它使用本机代码,但您不必编写任何内容 - 它已经为您完成了.


编辑:如果您要做的只是验证用户名/密码,那么我相信JNDI/LDAP方向可能对您有用 - 我之前在Java AS/400上做过这个,尽管我对此并不满意最终的结果.

如果您希望O/S将您的JVM进程识别为特定用户的凭证,那么您将需要某种形式的对非可移植本机API的访问.

顺便说一句,我们谈论的是什么O/S.


编辑2:我将发布我使用LDAP验证用户名/密码的方式的片段,关于你正在追求的机会/密码; 这些都是从我的代码中提取的,不能直接编译.

这是我写过的第一个Java代码,请怜悯:

import java.security.*;
import java.util.*;

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

...

private Hashtable                       masterEnv;          // master environment settings
private String                          authMethod;         // default authentication method

...

public void init() {
    // NOTE: Important to use a non-pooled context and a clone of the environment so that this authenticated
    //       connection is not returned to the pool and used for other operations
    masterEnv=new Hashtable();
    masterEnv.put(Context.INITIAL_CONTEXT_FACTORY,ldapFactory);
    masterEnv.put(Context.PROVIDER_URL,providerUrl);
    masterEnv.put(Context.SECURITY_PROTOCOL,secProtocol);
    masterEnv.put(Context.REFERRAL,"follow");
    masterEnv.put("com.sun.jndi.ldap.connect.pool","false");

    authMethod=System.getProperty("authenticationMethod","simple");
    }

...

private void verifyUserPassword(String ui, String pw, String am) throws NameNotFoundException, AuthenticationException, AuthenticationNotSupportedException, NamingException, NamingException {
    // ui=user ID
    // pw=password
    // am=authentication method

    DirContext      lc=null;                                // ldap context object
    Hashtable       le;                                     // ldap environment object

    if(am.length()==0) { am=authMethod; }

    le=(Hashtable)masterEnv.clone();
    le.put(Context.SECURITY_AUTHENTICATION,am);
    le.put(Context.SECURITY_PRINCIPAL     ,ui);
    le.put(Context.SECURITY_CREDENTIALS   ,pw);
    lc=new InitialDirContext(le);
    lc.close();
    }
Run Code Online (Sandbox Code Playgroud)