Example usage for javax.naming Context SECURITY_CREDENTIALS

List of usage examples for javax.naming Context SECURITY_CREDENTIALS

Introduction

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

Prototype

String SECURITY_CREDENTIALS

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the credentials of the principal for authenticating the caller to the service.

Usage

From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java

public DirContext getDirContext() {
    DirContext ctx = null;//w  w w.  jav  a 2  s .  co  m
    String cadena = "uid=" + user + "," + context;
    Hashtable<String, String> entorno = new Hashtable<String, String>();

    entorno.put(Context.PROVIDER_URL, server);
    entorno.put(Context.SECURITY_PRINCIPAL, cadena);
    entorno.put(Context.SECURITY_CREDENTIALS, password);
    entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext);

    try {
        ctx = new InitialDirContext(entorno);
    } catch (NamingException e) {
        logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault()));
    }

    return ctx;
}

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

public boolean authenticateUser(String userLogin, UserEdit edit, String password) {
    Hashtable env = new Hashtable();
    InitialDirContext ctx;/*from w  w w.  ja  va 2 s.  c  om*/

    String INIT_CTX = "com.sun.jndi.ldap.LdapCtxFactory";
    String MY_HOST = getLdapHost() + ":" + getLdapPort();
    String cn;
    boolean returnVal = false;

    if (!password.equals("")) {

        env.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
        env.put(Context.PROVIDER_URL, MY_HOST);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, "secret");

        String[] returnAttribute = { "ou" };
        SearchControls srchControls = new SearchControls();
        srchControls.setReturningAttributes(returnAttribute);
        srchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(userLogin) + "))";

        try {
            ctx = new InitialDirContext(env);
            NamingEnumeration answer = ctx.search(getBasePath(), searchFilter, srchControls);
            String trobat = "false";

            while (answer.hasMore() && trobat.equals("false")) {

                SearchResult sr = (SearchResult) answer.next();
                String dn = sr.getName().toString() + "," + getBasePath();

                // Second binding
                Hashtable authEnv = new Hashtable();
                try {
                    authEnv.put(Context.INITIAL_CONTEXT_FACTORY, INIT_CTX);
                    authEnv.put(Context.PROVIDER_URL, MY_HOST);
                    authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
                    authEnv.put(Context.SECURITY_PRINCIPAL, sr.getName() + "," + getBasePath());
                    authEnv.put(Context.SECURITY_CREDENTIALS, password);
                    try {
                        DirContext authContext = new InitialDirContext(authEnv);
                        returnVal = true;
                        trobat = "true";
                        authContext.close();
                    } catch (AuthenticationException ae) {
                        M_log.info("Access forbidden");
                    }

                } catch (NamingException namEx) {
                    M_log.info("User doesn't exist");
                    returnVal = false;
                    namEx.printStackTrace();
                }
            }
            if (trobat.equals("false"))
                returnVal = false;

        } catch (NamingException namEx) {
            namEx.printStackTrace();
            returnVal = false;
        }
    }
    return returnVal;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * create new user in LDAP-directory.//from w  w w  . j a v  a2 s.  com
 *
 * @param inBenutzer
 *            User object
 * @param inPasswort
 *            String
 */
public void createNewUser(User inBenutzer, String inPasswort)
        throws NamingException, NoSuchAlgorithmException, IOException {

    if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) {
        Hashtable<String, String> env = getLdapConnectionSettings();
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

        LdapUser dr = new LdapUser();
        dr.configure(inBenutzer, inPasswort, getNextUidNumber());
        DirContext ctx = new InitialDirContext(env);
        ctx.bind(getUserDN(inBenutzer), dr);
        ctx.close();
        setNextUidNumber();
        Helper.setMeldung(null, Helper.getTranslation("ldapWritten") + " "
                + serviceManager.getUserService().getFullName(inBenutzer), "");
        /*
         * check if HomeDir exists, else create it
         */
        logger.debug("HomeVerzeichnis pruefen");
        URI homePath = URI.create(getUserHomeDirectory(inBenutzer));
        if (!new File(homePath).exists()) {
            logger.debug("HomeVerzeichnis existiert noch nicht");
            serviceManager.getFileService().createDirectoryForUser(homePath, inBenutzer.getLogin());
            logger.debug("HomeVerzeichnis angelegt");
        } else {
            logger.debug("HomeVerzeichnis existiert schon");
        }
    } else {
        Helper.setMeldung(Helper.getTranslation("ldapIsReadOnly"));
    }
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapService.java

void activate(Map<?, ?> configuration) throws NamingException {
    this.idSuffix = (String) configuration.get(CONFIG_ID_SUFFIX);
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    this.userSearchBase = (String) configuration.get(CONFIG_USER_SEARCH_BASE);
    this.userFilter = (String) configuration.get(CONFIG_USER_FILTER);

    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

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

    if (managerDN != null) {
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
        searchEnvironment.put(Context.SECURITY_PRINCIPAL, managerDN);
        searchEnvironment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else/*from w w w  .j a  va 2  s . c om*/
        searchEnvironment.put(Context.SECURITY_AUTHENTICATION, "none");
}

From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

@Override
public User authenticate(Credentials credentials) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.authenticate(Credentials credentials)");
    }/*from w w w .j av a 2  s.  com*/
    String userName = credentials.getUsername();
    String passwordEncoded = credentials.getPassword();
    byte[] decodedBytes = Base64.decodeBase64(passwordEncoded);
    String password = new String(decodedBytes);
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfig.getLdapContextFactory());
    env.put(Context.PROVIDER_URL, ldapConfig.getLdapUrl());
    env.put(Context.SECURITY_PRINCIPAL, getUserPrincipal(userName));
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dc = null;
    try {
        dc = new InitialDirContext(env);
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Success for " + userName);
        }
        return getUser(credentials, dc);
    } catch (Exception e) {
        e.printStackTrace();
        if (isDebugEnabled) {
            S_LOGGER.debug("authenticate() Login Failed for " + userName);
        }
        return new User();
    } finally {
        try {
            if (dc != null) {
                dc.close();
            }
        } catch (NamingException e) {
            throw new PhrescoException(e);
        }
    }
}

From source file:de.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSun() throws NamingException {
    Hashtable<String, String> contextParams = new Hashtable<String, String>();
    contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
    contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
    contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
    contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    DirContext dirContext = new InitialDirContext(contextParams);

    Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" });
    Attribute attribute = attributes.get("namingContexts");
    NamingEnumeration<?> all = attribute.getAll();
    while (all.hasMore()) {
        String next = (String) all.next();
        logger.info(next);/*from w w w .  ja va2  s  . c  o m*/
    }
}

From source file:org.apache.ftpserver.usermanager.LdapUserManager.java

/**
 * Instantiate LDAP based <code>UserManager</code> implementation.
 */// www.j a  va 2s.c  o m
public void configure(Configuration config) throws FtpException {

    try {

        // get admin name 
        m_adminName = config.getString("admin", "admin");

        // get ldap parameters
        String url = config.getString("ldap-url");
        String admin = config.getString("ldap-admin-dn");
        String password = config.getString("ldap-admin-password");
        String auth = config.getString("ldap-authentication", "simple");

        m_userBaseDn = config.getString("ldap-user-base-dn");

        // create connection
        Properties adminEnv = new Properties();
        adminEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        adminEnv.setProperty(Context.PROVIDER_URL, url);
        adminEnv.setProperty(Context.SECURITY_AUTHENTICATION, auth);
        adminEnv.setProperty(Context.SECURITY_PRINCIPAL, admin);
        adminEnv.setProperty(Context.SECURITY_CREDENTIALS, password);
        m_adminContext = new InitialDirContext(adminEnv);

        // create objectClass attribute
        m_objClassAttr = new BasicAttribute(OBJ_CLASS, false);
        m_objClassAttr.add("javaObject");
        m_objClassAttr.add("top");

        m_log.info("LDAP user manager opened.");
    } catch (FtpException ex) {
        throw ex;
    } catch (Exception ex) {
        m_log.fatal("LdapUserManager.configure()", ex);
        throw new FtpException("LdapUserManager.configure()", ex);
    }
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

public DirContext getDirContext(Properties props) throws NamingException {
    if (this.ctx == null) {
        synchronized (this) {
            if (this.ctx == null) {
                log.debug("[getDirContext] creating new connection");
                Collection rtn = new TreeSet();
                Hashtable ldapEnv = new Hashtable();
                String ldapDriver = props.getProperty("ldapDriver"),
                        ldapHostURL = props.getProperty("ldapHostURL"),
                        ldapAuthType = props.getProperty("ldapAuthType"),
                        ldapPasswd = props.getProperty("ldapPasswd"),
                        ldapTreePathToDN = props.getProperty("ldapTreePathToDN");
                ldapTreePathToDN = (ldapTreePathToDN == null) ? "" : ldapTreePathToDN;
                ldapPasswd = (ldapPasswd == null) ? "" : ldapPasswd;
                ldapPasswd = (ldapPasswd.matches("^\\s*$")) ? "" : ldapPasswd;
                ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapDriver);
                ldapEnv.put(Context.PROVIDER_URL, ldapHostURL);
                ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapAuthType);
                ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapTreePathToDN);
                ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapPasswd);
                this.ctx = new InitialDirContext(ldapEnv);
            }//from  w  ww  .  j  ava 2  s.co  m
        }
    }
    return this.ctx;
}

From source file:net.identio.server.service.authentication.ldap.LdapConnectionFactory.java

private InitialLdapContext createContext(LdapAuthMethod ldapAuthMethod, String userDn, String password)
        throws NamingException {

    LOG.debug("Begin creation of an LDAP connection to: {}", ldapAuthMethod.getName());

    int currentUrlIndexTs = currentUrlIndex;

    String currentUrl = ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs);

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

    if (currentUrl.startsWith("ldaps://")) {

        // Add a custom SSL Socket factory to validate server CA
        env.put("java.naming.ldap.factory.socket",
                "net.identio.server.service.authentication.ldap.LdapSslSocketFactory");
    }//from w  ww .ja v a2s .  c  o  m

    if (userDn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, userDn);
        env.put(Context.SECURITY_CREDENTIALS, password);
    }

    InitialLdapContext ctx;

    try {
        ctx = new InitialLdapContext(env, null);
    } catch (CommunicationException e) {

        LOG.error("Error when contacting LDAP server {}", ldapAuthMethod.getLdapUrl().get(currentUrlIndexTs));

        if (ldapAuthMethod.getLdapUrl().size() > 1) {
            int newCurrentUrlIndex = currentUrlIndexTs < ldapAuthMethod.getLdapUrl().size() - 1
                    ? currentUrlIndexTs + 1
                    : 0;

            LOG.error("Switching to LDAP server {}", ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            currentUrlIndex = newCurrentUrlIndex;

            env.put(Context.PROVIDER_URL, ldapAuthMethod.getLdapUrl().get(newCurrentUrlIndex));

            ctx = new InitialLdapContext(env, null);
        } else {
            throw e;
        }
    }

    return ctx;
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();/*from w w w  .j av a2s  . c  o m*/
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}