7

我正在为 Java 编写一个带有 Play2 的 webApp,并希望使用 LDAP 进行用户身份验证......我是 LDAP 新手,实际上不知道它是如何工作的以及如何在 Play 中使用它......

现在我发现这个插件应该可以解决问题,但我找不到任何使用 LDAP 身份验证的示例。你知道任何可以帮助我迈出第一步的教程吗?

我也看到了这篇博客文章,看起来不错,但没有使用播放身份验证插件,所以它可能没有那么灵活? http://www.philipp.haussleiter.de/2013/07/adding-ldap-authentication-to-a-play-2-application/

4

1 回答 1

5

我有一个使用 LDAP 和播放框架对用户进行身份验证的示例。这是代码希望这会有所帮助

public class ActiveDirectoryServices {

  public static final String ldapURL = Play.application().configuration().getString("ActiveDirectory.url");
  public static final String domainName =   Play.application().configuration().getString("ActoveDirectory.DomainName");
  public static final int timeout =         Play.application().configuration().getInt("ActoveDirectory.timeout");

  public static Promise<Boolean> authenticate(String username, String password) throws AuthenticationException, CommunicationException, NamingException{

     Hashtable<String, String> env = new Hashtable<String,String>();     

     env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
     env.put("com.sun.jndi.ldap.connect.timeout", ""+(timeout*1000));
     env.put(Context.PROVIDER_URL, ldapURL);
     env.put(Context.SECURITY_AUTHENTICATION, "simple");
     env.put(Context.SECURITY_PRINCIPAL, username+domainName);
     env.put(Context.SECURITY_CREDENTIALS, password);

     DirContext authContext = null; 
     authContext = new InitialDirContext(env);        
     return Promise.pure(Boolean.TRUE);                         
   }

}

然后在控制器中我使用上面的代码如下:

try {

    Promise<Boolean> promiseActiveDirectoryCheck = ActiveDirectoryServices.authenticate(userName, password);
      return promiseActiveDirectoryCheck.flatMap(response -> {

      if(response){                           
        return Promise.pure(ok("access granted"));
      }


  });

}catch (AuthenticationException exp) {
  return Promise.pure(ok("access denied"));

}catch (CommunicationException exp) {
  return Promise.pure(ok("The active directory server is not reachable"));

}catch (NamingException exp) {
  return Promise.pure(ok("active directory domain name does not exist"));

}
于 2015-09-03T19:09:58.343 回答