Example usage for javax.naming Context SECURITY_PRINCIPAL

List of usage examples for javax.naming Context SECURITY_PRINCIPAL

Introduction

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

Prototype

String SECURITY_PRINCIPAL

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

Click Source Link

Document

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

Usage

From source file:org.lsc.jndi.JndiServices.java

private void logConnectingTo(Properties connProps) {
    if (LOGGER.isInfoEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Connecting to LDAP server ");
        sb.append(connProps.getProperty(Context.PROVIDER_URL));

        // log identity used to connect
        if (connProps.getProperty(Context.SECURITY_AUTHENTICATION) == null
                || connProps.getProperty(Context.SECURITY_AUTHENTICATION).equals("none")) {
            sb.append(" anonymously");
        } else {//  ww w  .  java 2 s . c  o m
            sb.append(" as ");
            sb.append(connProps.getProperty(Context.SECURITY_PRINCIPAL));
        }

        // using TLS ?
        if (connProps.get(TLS_CONFIGURATION) != null && (Boolean) connProps.get(TLS_CONFIGURATION)) {
            sb.append(" with STARTTLS extended operation");
        }

        LOGGER.info(sb.toString());
    }
}

From source file:io.apiman.gateway.engine.policies.BasicAuthLDAPTest.java

private DirContext createContext() throws NamingException {
    // Create a environment container
    Hashtable<Object, Object> env = new Hashtable<>();

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();

    // Create a new context pointing to the partition
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    // Let's open a connection on this partition
    InitialContext initialContext = new InitialContext(env);

    // We should be able to read it
    DirContext appRoot = (DirContext) initialContext.lookup("");
    Assert.assertNotNull(appRoot);//from   ww  w  .  j  a  va2  s  .c  o  m

    return appRoot;
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in
 * mixed case partitions were not able to authenticate properly.  This test case creates
 * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA
 * issue and attempts to authenticate as that user.
 *
 * @throws Exception if the user cannot authenticate or test fails
 *///from  ww  w .  j  av a2  s. co m
@Test
public void testUserAuthOnMixedCaseSuffix() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/dc=aPache,dc=org");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    InitialDirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes("");
    assertTrue(attrs.get("dc").get().equals("aPache"));

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.createSubcontext("cn=Kate Bush", user);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "Aerial");
    env.put(Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org");

    InitialDirContext userCtx = new InitialDirContext(env);
    assertNotNull(userCtx);

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:nl.nn.adapterframework.webcontrol.LoginFilter.java

private boolean checkUsernamePassword(String username, String password, String authorizePathMode) {
    String dnUser = Misc.replace(ldapAuthUserBase, "%UID%", username);

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapAuthUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, dnUser);
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = null;/*w  w  w. j a v  a2  s . c  o  m*/
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }

        if (authorizePathMode == null) {
            return true;
        } else {
            if (authorizePathMode.equals(AUTH_PATH_MODE_OBSERVER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthObserverBase)) {
                    return true;
                }
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_DATAADMIN)) {
                if (isMemberOf(ctx, dnUser, ldapAuthDataAdminBase)) {
                    return true;
                }
            }
            if (authorizePathMode.equals(AUTH_PATH_MODE_TESTER)) {
                if (isMemberOf(ctx, dnUser, ldapAuthTesterBase)) {
                    return true;
                }
            }
        }
    } catch (AuthenticationException e) {
        return false;
    } catch (Exception e) {
        log.warn("LoginFilter caught Exception", e);
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                log.warn("LoginFilter caught Exception", e);
            }
        }
    }
    return false;
}

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

/**
 * check if User already exists on system.
 *
 * @param inLogin/*from www  . j a  v a  2s.co  m*/
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.apache.axis.providers.java.EJBProvider.java

/**
 * Common routine to do the JNDI lookup on the Home interface object
 * username and password for jndi lookup are got from the configuration or from
 * the messageContext if not found in the configuration
 *///from   ww  w. ja v a  2s  .  c  o m
private Object getEJBHome(SOAPService serviceHandler, MessageContext msgContext, String beanJndiName)
        throws AxisFault {
    Object ejbHome = null;

    // Set up an InitialContext and use it get the beanJndiName from JNDI
    try {
        Properties properties = null;

        // collect all the properties we need to access JNDI:
        // username, password, factoryclass, contextUrl

        // username
        String username = getStrOption(jndiUsername, serviceHandler);
        if ((username == null) && (msgContext != null))
            username = msgContext.getUsername();
        if (username != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.SECURITY_PRINCIPAL, username);
        }

        // password
        String password = getStrOption(jndiPassword, serviceHandler);
        if ((password == null) && (msgContext != null))
            password = msgContext.getPassword();
        if (password != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.SECURITY_CREDENTIALS, password);
        }

        // factory class
        String factoryClass = getStrOption(jndiContextClass, serviceHandler);
        if (factoryClass != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryClass);
        }

        // contextUrl
        String contextUrl = getStrOption(jndiURL, serviceHandler);
        if (contextUrl != null) {
            if (properties == null)
                properties = new Properties();
            properties.setProperty(Context.PROVIDER_URL, contextUrl);
        }

        // get context using these properties 
        InitialContext context = getContext(properties);

        // if we didn't get a context, fail
        if (context == null)
            throw new AxisFault(Messages.getMessage("cannotCreateInitialContext00"));

        ejbHome = getEJBHome(context, beanJndiName);

        if (ejbHome == null)
            throw new AxisFault(Messages.getMessage("cannotFindJNDIHome00", beanJndiName));
    }
    // Should probably catch javax.naming.NameNotFoundException here 
    catch (Exception exception) {
        entLog.info(Messages.getMessage("toAxisFault00"), exception);
        throw AxisFault.makeFault(exception);
    }

    return ejbHome;
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

@Override
public String getBindedUserDn() throws LDAPException {
    if (!isClosed()) {
        try {/*  w  ww.j  a  v a  2 s.  c  o  m*/
            return (String) getConn().getEnvironment().get(Context.SECURITY_PRINCIPAL);
        } catch (NamingException nex) {
            throw handleNamingException(nex, "Cannot get binded user DN.");
        }
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

public LdapContext getContextWithCredentials(String userDN, String password)
        throws UserStoreException, NamingException, AuthenticationException {
    LdapContext context = null;//from  w  w  w.  j  a v a2 s .  com

    //create a temp env for this particular authentication session by copying the original env
    Hashtable<String, String> tempEnv = new Hashtable<String, String>();
    for (Object key : environment.keySet()) {
        tempEnv.put((String) key, (String) environment.get(key));
    }
    //replace connection name and password with the passed credentials to this method
    tempEnv.put(Context.SECURITY_PRINCIPAL, userDN);
    tempEnv.put(Context.SECURITY_CREDENTIALS, password);

    //if dcMap is not populated, it is not DNS case
    if (dcMap == null) {

        //replace environment properties with these credentials
        context = new InitialLdapContext(tempEnv, null);

    } else if (dcMap != null && dcMap.size() != 0) {
        try {
            //first try the first entry in dcMap, if it fails, try iteratively
            Integer firstKey = dcMap.firstKey();
            SRVRecord firstRecord = dcMap.get(firstKey);
            //compose the connection URL
            tempEnv.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(firstRecord));
            context = new InitialLdapContext(tempEnv, null);

        } catch (AuthenticationException e) {
            throw e;

        } catch (NamingException e) {
            log.error("Error obtaining connection to first Domain Controller." + e.getMessage(), e);
            log.info("Trying to connect with other Domain Controllers");

            for (Integer integer : dcMap.keySet()) {
                try {
                    SRVRecord srv = dcMap.get(integer);
                    environment.put(Context.PROVIDER_URL, getLDAPURLFromSRVRecord(srv));
                    context = new InitialLdapContext(environment, null);
                    break;
                } catch (AuthenticationException e2) {
                    throw e2;
                } catch (NamingException e1) {
                    if (integer == (dcMap.lastKey())) {
                        log.error("Error obtaining connection for all " + integer + " Domain Controllers."
                                + e1.getMessage(), e1);
                        throw new UserStoreException("Error obtaining connection. " + e1.getMessage(), e1);
                    }
                }
            }
        }
    }
    return (context);
}

From source file:com.communote.server.test.ldap.AbstractApacheDSServer.java

/**
 * Sets the contexts for this base class. Values of user and password used to set the respective
 * JNDI properties. These values can be overriden by the overrides properties.
 *
 * @param user/*w ww  .ja v a 2s.  co m*/
 *            the username for authenticating as this user
 * @param passwd
 *            the password of the user
 * @throws Exception
 *             if there is a failure of any kind
 */
protected void setContexts(String user, String passwd) throws Exception {
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, getDirectoryService());
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    setContexts(env);
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

@Test
public void testFailureWithUnsupportedControl() throws Exception {
    Control unsupported = new OpaqueControl("1.1.1.1");
    unsupported.setCritical(true);//from  ww w.ja v a  2s  .  co m

    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

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

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/ou=system");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    InitialLdapContext ctx = new InitialLdapContext(env, null);

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    try {
        ctx.createSubcontext("cn=Kate Bush", user);
        fail();
    } catch (OperationNotSupportedException e) {
    }

    unsupported.setCritical(false);
    ctx.setRequestControls(JndiUtils.toJndiControls(getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[] { unsupported }));

    DirContext kate = ctx.createSubcontext("cn=Kate Bush", user);
    assertNotNull(kate);
    assertTrue(ArrayUtils.isEquals(Asn1StringUtils.getBytesUtf8("Aerial"),
            kate.getAttributes("").get("userPassword").get()));

    ctx.destroySubcontext("cn=Kate Bush");
}