检查 Java 应用程序中使用 Active Directory 登录的用户

tma*_*ace 3 java ldap active-directory

因此,我环顾四周以找到我正在寻找的答案,尤其是在这个网站上,但没有任何运气或没有办法获得我想要的这个应用程序。

这是一个 java 应用程序,我正在尝试与 Windows Server 2012 R2 中的 Active Directory 进行交互,因此如果用户已使用 Active Directory 登录到其计算机,则无需登录此 java 应用程序。

我听说如果用户使用 Active Directory 登录,机器上就会有某种令牌,我希望能够检查该令牌,获取登录用户的用户名,并使用该用户名(忽略密码)将它们登录到 java 应用程序。我想这样做,而无需针对 AD 服务器进行身份验证。

我不确定这是否是针对此 java 应用程序管理 Active Directory 的最有效方法,但考虑到我的情况,这就是我所需要的。

欢迎链接,如果之前有人问过这个问题,我很抱歉。

编辑:这是假设我唯一可用的信息是 Active Directory 用户的用户名,它将与 java 应用程序中的用户名匹配。我也有服务器凭据,但我试图避免以任何形式存储服务器的密码。

tma*_*ace 5

弄清楚了。使用 System.getenv("USERDNSDOMAIN") 为我们提供了 user@domain,如果用户未使用 Active Directory 登录,则该 user@domain 为 null,在本例中这就足够了。然后我们使用 JAAS 和服务器配置文件来获取 LoginContext,它从登录用户那里获取主题。

希望这对某人有帮助!

例如,代码如下:

//this returns the logged in user if they're authenticated with the ldap server (Active Directory)
public javax.security.auth.Subject getSubject()
{
    String ldapServer = System.getenv("USERDNSDOMAIN");

    if (ldapServer == null)
    {
      Logger.error("No \"USERDNSDOMAIN\" environment variable found");
      return null;
    }

    System.setProperty("java.security.auth.login.config", "jaas.conf");
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "true");
    try
    {
      LoginContext loginCtx = new LoginContext("Server", new TextCallbackHandler());
      loginCtx.login();
      return loginCtx.getSubject();
    }
}
Run Code Online (Sandbox Code Playgroud)

以及 jaas.conf 文件的内容:

Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=false
useTicketCache=true;
};
Run Code Online (Sandbox Code Playgroud)