Example usage for javax.naming Context SECURITY_AUTHENTICATION

List of usage examples for javax.naming Context SECURITY_AUTHENTICATION

Introduction

In this page you can find the example usage for javax.naming Context SECURITY_AUTHENTICATION.

Prototype

String SECURITY_AUTHENTICATION

To view the source code for javax.naming Context SECURITY_AUTHENTICATION.

Click Source Link

Document

Constant that holds the name of the environment property for specifying the security level to use.

Usage

From source file:CreateJavaSchema.java

/**
 * Signs on to directory server using parameters supplied to program.
 * @return The initial context to the server.
 *//*from   w  w  w  .  j  ava  2  s .co  m*/
private DirContext signOn() throws NamingException {
    if (dn != null && auth == null) {
        auth = "simple"; // use simple for Netscape
    }

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.REFERRAL, "follow");

    if (auth != null) {
        env.put(Context.SECURITY_AUTHENTICATION, auth);
        env.put(Context.SECURITY_PRINCIPAL, dn);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
    }

    // Workaround for Netscape schema bugs
    if (netscapebug) {
        env.put("com.sun.naming.netscape.schemaBugs", "true");
    }

    // LDAP protocol tracing
    if (traceLdap) {
        env.put("com.sun.jndi.ldap.trace.ber", System.err);
    }

    return new InitialDirContext(env);
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

/**
 * Creates an LDAP authenticator for the specified server, base DN and given
 * identifier attribute/*from   w ww  . ja v  a  2  s .c  o  m*/
 * 
 * @param baseUrl
 *            LDAP server URL
 * @param baseDn
 *            LDAP base DN
 * @param ldapSecurityPrincipal
 *            LDAP Security Principal
 * @param ldapSecurityCredentials
 *            Credentials for Security Principal
 * @param ldapRoleAttr
 *            Name of the LDAP attribute that defines the role
 * @param idAttr
 *            LDAP user identifier attribute
 */
public CustomLdapAuthenticationHandler(String baseUrl, String baseDn, String ldapSecurityPrincipal,
        String ldapSecurityCredentials, String ldapRoleAttr, String idAttr) {
    // Set public variables      
    this.baseDn = baseDn;
    this.idAttr = idAttr;
    this.ldapRoleAttr = ldapRoleAttr;
    this.baseUrl = baseUrl;
    this.ldapSecurityPrincipal = ldapSecurityPrincipal;
    this.ldapSecurityCredentials = ldapSecurityCredentials;
    if (CustomLdapAuthenticationHandler.credentialCache == null) {
        CacheManager singletonManager = CacheManager.create();
        CustomLdapAuthenticationHandler.credentialCache = new Cache("credentialCache", 500, false, false, 3600,
                1800);
        singletonManager.addCache(CustomLdapAuthenticationHandler.credentialCache);
    }

    // Initialise the LDAP environment
    env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, baseUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (!ldapSecurityPrincipal.equals("")) {
        env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
        env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);
    }

}

From source file:ldap.SearchUtility.java

/**
 * open the directory connection.//from   www  .  j ava2  s . c  o  m
 *
 * @param url
 * @param tracing
 * @return
 * @throws javax.naming.NamingException
 */
private DirContext setupJNDIConnection(String url, String userDN, String password, boolean tracing)
        throws NamingException {
    /*
    * First, set up a large number of environment variables to sensible default valuse
    */

    Hashtable env = new Hashtable();
    // sanity check
    if (url == null)
        throw new NamingException("URL not specified in openContext()!");

    // set the tracing level now, since it can't be set once the connection is open.
    if (tracing)
        env.put("com.sun.jndi.ldap.trace.ber", System.err); // echo trace to standard error output

    env.put("java.naming.ldap.version", "3"); // always use ldap v3 - v2 too limited
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // use default jndi provider
    env.put("java.naming.ldap.deleteRDN", "false"); // usually what we want
    env.put(Context.REFERRAL, "ignore"); //could be: follow, ignore, throw
    env.put("java.naming.ldap.derefAliases", "finding"); // could be: finding, searching, etc.
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 'simple' = username + password
    env.put(Context.SECURITY_PRINCIPAL, userDN); // add the full user dn
    env.put(Context.SECURITY_CREDENTIALS, password); // stupid jndi requires us to cast this to a string-
    env.put(Context.PROVIDER_URL, url); // the ldap url to connect to; e.g. "ldap://ca.com:389"

    /*
    *  Open the actual LDAP session using the above environment variables
    */

    DirContext newContext = new InitialDirContext(env);

    if (newContext == null)
        throw new NamingException(
                "Internal Error with jndi connection: No Context was returned, however no exception was reported by jndi.");

    return newContext;

}

From source file:com.aurel.track.util.LdapUtil.java

public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword)
        throws NamingException {
    boolean userIsOK = false;
    ArrayList<String> trace = new ArrayList<String>();

    trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<");

    if (siteBean.getLdapServerURL().startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
    }//from w  w w  . ja v a 2  s  .  c om
    // get the CN
    String keyDn = getCn(siteBean, loginName);

    try {
        if (keyDn != null) {
            trace.add("Using keyDn >" + keyDn + "<");
            // Set up the environment for creating the initial context
            Hashtable<String, String> env = new Hashtable<String, String>(11);
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL());
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, keyDn);
            env.put(Context.SECURITY_CREDENTIALS, ppassword);
            // Create initial context
            DirContext itest = new InitialDirContext(env);
            itest.close();
            // user was validated
            userIsOK = true;
        }
        return userIsOK;
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.warn(msg);
        }
        throw e;
    }
}

From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java

protected boolean userExists(String id) {
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    try {//from   w  w  w  . jav  a  2 s .c om
        DirContext ctx = new InitialDirContext(env);

        /*
         * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        /*
         * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
         */

        String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

        /* Execute the search, starting at the directory level of Users */

        NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

        /* All we need to know is if there were any hits at all. */

        if (hits.hasMore()) {
            hits.close();
            ctx.close();
            return true;
        } else {
            hits.close();
            ctx.close();
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *///from w w  w. j a  va2s .c o  m
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for getting the LDAP COntext based on the host,username, password
 * @param host/*w ww.  jav a 2 s .c o m*/
 * @param adminName
 * @param adminPassword
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static LdapContext getLDAPContext(String host, String adminName, String adminPassword)
        throws NamingException {
    //Logger.info("Creating LDAP Context", LDAPUtils.class);
    Hashtable props = System.getProperties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.SECURITY_AUTHENTICATION, LDAP_SECURITY_AUTHENTICATION);
    props.put(Context.SECURITY_PRINCIPAL, adminName);
    props.put(Context.SECURITY_CREDENTIALS, adminPassword);
    props.put(Context.PROVIDER_URL, host);
    if (!StringUtils.isNull(LDAPConfigUtils.getTrustStorePath())) {
        System.setProperty("javax.net.ssl.trustStore", LDAPConfigUtils.getTrustStorePath());
        props.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    //Logger.info("Completed creating LDAP Context for host ["+host+"]", LDAPUtils.class);
    return (new InitialLdapContext(props, null));
}

From source file:iplatform.admin.ui.server.auth.ad.ActiveDirectoryLdapAuthenticationProvider.java

private DirContext bindAsUser(String username, String password) {
    // TODO. add DNS lookup based on domain
    final String bindUrl = url;

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    String bindPrincipal = createBindPrincipal(username);
    env.put(Context.SECURITY_PRINCIPAL, bindPrincipal);
    env.put(Context.PROVIDER_URL, bindUrl);
    env.put(Context.SECURITY_CREDENTIALS, password);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.OBJECT_FACTORIES, DefaultDirObjectFactory.class.getName());

    try {//w ww. j  a  v a 2s  .  c  o  m
        return contextFactory.createContext(env);
    } catch (NamingException e) {
        if ((e instanceof AuthenticationException) || (e instanceof OperationNotSupportedException)) {
            handleBindException(bindPrincipal, e);
            throw badCredentials(e);
        } else {
            throw LdapUtils.convertLdapException(e);
        }
    }
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void readConfig() throws InitializationException {

    String configFile = "/opt/midpoint/opendj-pwdpusher.xml";
    if (System.getProperty("config") != null) {
        configFile = System.getProperty("config");
    }/*from  w ww . java 2 s. c o  m*/

    File f = new File(configFile);
    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException("Config file " + configFile + " does not exist or is not readable");
    }

    try {
        XMLConfiguration config = new XMLConfiguration(f);

        String notifierDN = "cn=" + config.getString("passwordpusher.statusNotifierName")
                + ",cn=Account Status Notification Handlers";
        String ldapURL = config.getString("passwordpusher.ldapServerURL");
        boolean ldapSSL = config.getBoolean("passwordpusher.ldapServerSSL");
        String ldapUsername = config.getString("passwordpusher.ldapServerUsername");
        String ldapPassword = config.getString("passwordpusher.ldapServerPassword");

        Hashtable<Object, Object> env = new Hashtable<Object, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL + "/cn=config");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        if (ldapSSL) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        try {
            DirContext context = new InitialDirContext(env);
            Attributes attr = context.getAttributes(notifierDN);

            this.endPoint = attr.get("ds-cfg-referrals-url").get(0).toString();
            this.username = attr.get("ds-cfg-midpoint-username").get(0).toString();
            this.password = attr.get("ds-cfg-midpoint-password").get(0).toString();
            this.pwdChangeDirectory = attr.get("ds-cfg-midpoint-passwordcachedir").get(0).toString();
        } catch (NamingException ne) {
            throw new InitializationException(
                    ERR_MIDPOINT_PWDSYNC_READING_CONFIG_FROM_LDAP.get(ne.getMessage()), ne);
        }
    } catch (ConfigurationException ce) {
        throw new InitializationException(ERR_MIDPOINT_PWDSYNC_PARSING_XML_CONFIG.get(ce.getMessage()), ce);
    }
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*from   w  ww . jav a 2s  . c om*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}