繁体   English   中英

使用 scala 或 java 进行 LDAP 身份验证

[英]LDAP authentication using scala or java

我在我的机器上创建了一个 LDAP 服务器,并在 LDAP 服务器中创建了一个用户作为管理员,我可以使用 URL 访问它,比如http://192.158.2.136/phpldapadmin ,现在我的应用程序中有一个登录页面以及什么我想要的是当有人输入用户名和密码时我希望我的应用程序从 LDAP 服务器验证这个用户,即我应该检查输入的任何用户名和密码是否存在于 LDAP 服务器中。到目前为止,我尝试使用apacheds-all但不能找到一种将用户名和密码发送到服务器的正确方法,有人可以告诉我如何在javascala执行此操作,我应该能够使用javascala作为客户端代码验证来自 LDAP 服务器的用户凭据。提前致谢! !

我终于得到了一个解决方案:

 object LDAPValidations {

    def validateForLDAP(username: String, passcode: String): Boolean = {

    val result = Try {
      var props = new Properties
      props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
      props.put(Context.PROVIDER_URL, "ldap://192.168.1.121:389")
      props.put(Context.SECURITY_PRINCIPAL, s"cn=$username,cn=staff,dc=myreutore,dc=local")
      props.put(Context.SECURITY_CREDENTIALS, "administrator")

      var context: InitialDirContext = new InitialDirContext(props)

      val controls: SearchControls = new SearchControls
      controls.setReturningAttributes(Array[String]("givenName", "sn", "memberOf", "cn"))
      controls.setSearchScope(SearchControls.SUBTREE_SCOPE)

      val answers: NamingEnumeration[SearchResult] = context.search("dc=myrtor,dc=local", s"cn=$username", controls)
      val result: SearchResult = answers.nextElement

      val user: String = result.getNameInNamespace
      props = new Properties
      props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
      props.put(Context.PROVIDER_URL, "ldap://192.168.1.121:389")
      props.put(Context.SECURITY_PRINCIPAL, user)
      props.put(Context.SECURITY_CREDENTIALS, passcode)
      context = new InitialDirContext(props)
    }
    result match {
      case Success(v) => true
      case Failure(v) => false
    }

  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM