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.hyperic.hq.product.jmx.MxUtil.java

public static JMXConnector getMBeanConnector(Properties config) throws MalformedURLException, IOException {

    String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL);
    Map map = new HashMap();

    String user = config.getProperty(PROP_JMX_USERNAME);
    String pass = config.getProperty(PROP_JMX_PASSWORD);

    map.put(JMXConnector.CREDENTIALS, new String[] { user, pass });

    // required for Oracle AS
    String providerPackages = config.getProperty(PROP_JMX_PROVIDER_PKGS);
    if (providerPackages != null)
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, providerPackages);

    if (jmxUrl == null) {
        throw new MalformedURLException(PROP_JMX_URL + "==null");
    }/* w ww . j a v a 2s .co  m*/

    if (jmxUrl.startsWith(PTQL_PREFIX)) {
        jmxUrl = getUrlFromPid(jmxUrl.substring(PTQL_PREFIX.length()));
    }

    JMXServiceURL url = new JMXServiceURL(jmxUrl);

    String proto = url.getProtocol();
    if (proto.equals("t3") || proto.equals("t3s")) {
        //http://edocs.bea.com/wls/docs92/jmx/accessWLS.html
        //WebLogic support, requires:
        //cp $WLS_HOME/server/lib/wljmxclient.jar pdk/lib/
        //cp $WLS_HOME/server/lib/wlclient.jar pdk/lib/
        map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
        map.put(Context.SECURITY_PRINCIPAL, user);
        map.put(Context.SECURITY_CREDENTIALS, pass);
    }

    JMXConnector connector = JMXConnectorFactory.connect(url, map);
    if (log.isDebugEnabled()) {
        log.debug("created new JMXConnector url=" + url + ", classloader="
                + Thread.currentThread().getContextClassLoader());
    }
    return connector;
}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void createSampleEntity() throws Exception {

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

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    Attributes entry = new BasicAttributes();
    Attribute obClassAttr = new BasicAttribute("objectClass");
    obClassAttr.add("inetOrgPerson");
    entry.put(obClassAttr);//from  w w  w . jav a 2  s  .  c om

    Attribute mailAttr = new BasicAttribute("mail");
    mailAttr.add(testUserId + "@wso2.com");
    entry.put(mailAttr);

    Attribute passAttr = new BasicAttribute("userPassword");
    passAttr.add("12345");
    entry.put(passAttr);

    Attribute snAttr = new BasicAttribute("sn");
    snAttr.add("dim");
    entry.put(snAttr);

    Attribute cnAttr = new BasicAttribute("cn");
    cnAttr.add("dim");
    entry.put(cnAttr);

    String dn = "uid=" + testUserId + "," + userBase;

    ctx.createSubcontext(dn, entry);
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;//from w  w  w. ja  v a 2  s  . c om
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        // Authenticate via SASL EXTERNAL mechanism using client X.509
        // certificate contained in JVM keystore
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(null);
        return true;
        // perform search for privileged attributes under authenticated context
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return false;
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return false;
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.apache.openaz.xacml.admin.view.components.LDAPPIPConfigurationComponent.java

protected void testLDAPConnection() {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, this.textFieldFactory.getValue());
    env.put(Context.PROVIDER_URL, this.textFieldProviderURL.getValue());
    env.put(Context.SECURITY_PRINCIPAL, this.textFieldPrincipal.getValue());
    env.put(Context.SECURITY_CREDENTIALS, this.textFieldCredentials.getValue());

    String auth = this.comboBoxAuthentication.getValue().toString();
    env.put(Context.SECURITY_AUTHENTICATION, auth);
    ///*from w  w w .jav a2s.  c o  m*/
    // Do we need to do anything?
    //
    /*
    if (auth.equals(LDAP_AUTH_ANONYMOUS)) {
               
    } else if (auth.equals(LDAP_AUTH_SIMPLE)) {
               
    } else if (auth.equals(LDAP_AUTH_SASL)) {
               
    }
    */

    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        new Notification("Success!", "Connection Established!", Type.HUMANIZED_MESSAGE, true)
                .show(Page.getCurrent());
    } catch (NamingException e) {
        logger.error(e);
        new Notification("Connection Failed", "<br/>" + e.getLocalizedMessage(), Type.ERROR_MESSAGE, true)
                .show(Page.getCurrent());
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException idontcare) { //NOPMD
        }
    }
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabase.java

private void assertSimpleCredentialsValid(final String username, final String password) throws Throwable {
    RetryPrivilegedAction action = new RetryPrivilegedAction() {
        protected Object doIt(InitialLdapContext context) {
            return null;
        }//  w w  w .j  a v a 2s . c o m

        protected InitialLdapContext getContext(String url) throws Exception {
            String userDn = ((ActiveDirectoryUser) getAccount(username)).getOriginalDn();
            Map<String, String> variables = new HashMap<String, String>(3);
            variables.put(Context.SECURITY_AUTHENTICATION, configuration.getUserAuthenticationType());
            variables.put(Context.SECURITY_PRINCIPAL, userDn);
            variables.put(Context.SECURITY_CREDENTIALS, password);
            return configuration.getInitialContext(url, variables);
        }
    };
    Object result = action.run();
    if (result instanceof Throwable) {
        throw (Throwable) result;
    }
}

From source file:ome.logic.LdapImpl.java

/**
 * Creates the initial context with no connection request controls in order
 * to check authentication. If authentication fails, this method throws
 * a {@link SecurityViolation}.//  w w  w . ja v  a2s.  c o m
 *
 * @return {@link javax.naming.ldap.LdapContext}
 */
@SuppressWarnings("unchecked")
private void isAuthContext(String username, String password) {

    Hashtable<String, String> env = new Hashtable<String, String>(5, 0.75f);
    try {
        env = (Hashtable<String, String>) ctx.getReadOnlyContext().getEnvironment();

        if (username != null && !username.equals("")) {
            env.put(Context.SECURITY_PRINCIPAL, username);
            if (password != null) {
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
        }
        new InitialLdapContext(env, null);
    } catch (AuthenticationException authEx) {
        throw new SecurityViolation("Authentication falilure! " + authEx.toString());
    } catch (NamingException e) {
        throw new SecurityViolation("Naming exception! " + e.toString());
    }
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return false if user or password is wrong
 *    /*w w w .j a  v  a2  s. c om*/
 * here we expand attributes: %u, %d, %s
 *    if defined userSearch, retrieve user's DN  and try to bind with it
 * @param username
 * @param password
 * @return
 */
private boolean ldapBind(String username, String password) {
    String userDN = null;
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // customize the field used to search the user.

            SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr == null) {
                log.info("Username " + username + " not found");
                return false;
            }

            userDN = sr.getNameInNamespace().trim();
            log.info("binding with dn:" + userDN);

        }
        // on failure, set the user DN with append
        if (userDN == null) {
            userDN = "uid=" + username + "," + baseDn;
        }
    } catch (Exception e) {
        log.error("Can't instantiate LdapInterface: " + e.getMessage());
        return false;
    }
    // Set up environment for creating 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, getLdapUrl());

    // Authenticate as  User and password  
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext ctx = new InitialDirContext(env);
        log.debug(ctx.lookup(userDN));
        ctx.close();
    } catch (AuthenticationException e) {
        log.info("User not authenticated: " + e.getMessage());
        return false;
    } catch (NamingException e) {
        log.warn("User not authenticated: problem while accessing ldap " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected DirContext getConnection() {
    //JNDI boilerplate to connect to an initial context
    DirContext context = (DirContext) contexts.get("context");
    if (context == null) {
        Hashtable jndienv = new Hashtable();
        jndienv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        jndienv.put(Context.SECURITY_AUTHENTICATION, "simple");
        if (url.startsWith("ldaps")) { // Handle SSL connections
            String newurl = url.substring(0, 4) + url.substring(5);
            jndienv.put(Context.SECURITY_PROTOCOL, "ssl");
            jndienv.put(Context.PROVIDER_URL, newurl);
        } else {//  www. j  av  a 2s. c o m
            jndienv.put(Context.PROVIDER_URL, url);
        }
        if (logonid != null)
            jndienv.put(Context.SECURITY_PRINCIPAL, logonid);
        if (logonpassword != null)
            jndienv.put(Context.SECURITY_CREDENTIALS, logonpassword);
        try {
            context = new InitialDirContext(jndienv);
        } catch (NamingException nex) {
            log.error("LDAPGroupStore: unable to get context", nex);
        }
        contexts.put("context", context);
    }
    return context;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithoutTLS(Hashtable<String, String> env, User user, String password) {
    if (ConfigCore.getBooleanParameter(ParameterCore.LDAP_USE_SIMPLE_AUTH, false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
        // TODO: test for password
    } else {//from   w w w . ja va 2 s . c om
        env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    logger.debug("ldap environment set");

    try {
        logger.debug("start classic ldap authentication");
        logger.debug("user DN is {}", buildUserDN(user));

        if (Objects.isNull(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST))) {
            logger.debug("ldap attribute to test is null");
            DirContext ctx = new InitialDirContext(env);
            ctx.close();
            return true;
        } else {
            logger.debug("ldap attribute to test is not null");
            DirContext ctx = new InitialDirContext(env);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get(ConfigCore.getParameter(ParameterCore.LDAP_ATTRIBUTE_TO_TEST));
            logger.debug("ldap attributes set");
            String test = (String) la.get(0);
            if (test.equals(ConfigCore.getParameter(ParameterCore.LDAP_VALUE_OF_ATTRIBUTE))) {
                logger.debug("ldap ok");
                ctx.close();
                return true;
            } else {
                logger.debug("ldap not ok");
                ctx.close();
                return false;
            }
        }
    } catch (NamingException e) {
        logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
        return false;
    }
}