Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login page using Java and LDAP

Tags:

java

ldap

i am having to do a login page in java and it must login using the credentials from LDAP, does anyone have any tutorials or examples i could use as i have no idea where to start

Thanks !


1 Answers

You should use spring-security which has dozen of utilities and tutorial.

Here is the link to the official documentation: http://forum.springsource.org/showthread.php?124263-Basic-LDAP-Example-For-Spring-Security-3-1

BTW, here is the code to bind to an ldap server in pure JNDI:

/**
 * Returns the ldap context.
 * 
 * @param user the user name
 * @param password the password
 * @return the prepared context
 * @throws NamingException in case of...
 */
protected LdapContext buildContext(final String user, final String password) throws NamingException {
    String providerURL = new StringBuffer(getLdapScheme()) //
            .append("://") //
            .append(getLdapHost()) //
            .append(":") //
            .append(getLdapPort()) //
            .append("/") //
            .append(getLdapRootDN()).toString();

    Hashtable<String, String> properties = new Hashtable<>();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    properties.put(Context.PROVIDER_URL, providerURL);

    if (!isEmpty(user)) {
        // basic authentication
        properties.put(Context.SECURITY_AUTHENTICATION, "simple");
        properties.put(Context.SECURITY_PRINCIPAL, user);
        properties.put(Context.SECURITY_CREDENTIALS, defaultIfEmpty(password, ""));
    } else {
        // anonymous connection
        properties.put(Context.SECURITY_AUTHENTICATION, "none");
    }

    Control[] controls = null;

    LOGGER.info("creating new ldap context [url:{}, user: {}]", providerURL, user);

    return new InitialLdapContext(properties, controls);
}
like image 96
poussma Avatar answered Aug 01 '26 15:08

poussma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!