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.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

/**
 * @param userDN Distinguished name of the user to be authenticated
 * @param password Password of the user to be authenticated
 * @return The LDAP connection context with logged in as the given user.
 * @throws NamingException If the user cannot be authenticated or connection issue occurs.
 *///from  w ww . j a  v a 2  s. c  om
LdapContext getContextWithCredentials(String userDN, String password) throws NamingException {
    LdapContext context;

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

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

From source file:com.zabbix.gateway.JMXItemChecker.java

@Override
public JSONArray getValues() throws ZabbixException {
    JSONArray values = new JSONArray();

    try {/*from  www .j av a  2 s .  com*/

        HashMap<String, Object> env = null;

        env = new HashMap<String, Object>();
        env.put(JMXConnector.CREDENTIALS, new String[] { username, password });

        if (protocol.equals("t3") || protocol.equals("t3s")) {
            env.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
            env.put(javax.naming.Context.SECURITY_PRINCIPAL, ((String[]) env.get(JMXConnector.CREDENTIALS))[0]);
            env.put(javax.naming.Context.SECURITY_CREDENTIALS,
                    ((String[]) env.get(JMXConnector.CREDENTIALS))[1]);
        }

        // Required by SSL
        if (protocol.equals("jmxs")) {
            env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory());
        }

        jmxc = ZabbixJMXConnectorFactory.connect(url, env);
        mbsc = jmxc.getMBeanServerConnection();

        for (String key : keys)
            values.put(getJSONValue(key));
    } catch (Exception e) {
        throw new ZabbixException(e);
    } finally {
        try {
            if (null != jmxc)
                jmxc.close();
        } catch (java.io.IOException exception) {
        }

        jmxc = null;
        mbsc = null;
    }

    return values;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Can probably be done more elegant too.
 *
 * @param userDN   real dn to the user.//from  ww w  .  jav  a  2s .  c  om
 * @param password the user's password
 * @return
 */
public boolean checkAuthentication(String userDN, String password) {
    if (password.trim().equals(""))
        return false;
    DirContext ctx2 = null;
    try {
        // See if the user authenticates.
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url + "/" + ldapBaseDN);
        env.put(Context.SECURITY_AUTHENTICATION, auth);
        env.put(Context.SECURITY_PRINCIPAL, userDN);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
        // Specify timeout to be 10 seconds, only on non SSL since SSL connections
        // break with a timeout.
        ctx2 = new InitialDirContext(env);
        log.info("Successfully logged in... " + userDN);
    } catch (Exception e) {
        log.error("Exception during login", e);
        return false;
    }

    finally {
        try {
            ctx2.close();
        } catch (NamingException ignore) {
        }
    }

    return true;
}

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

public boolean getUser(UserEdit edit) {

    if (!userExists(edit.getEid()))
        return false;

    env.put(Context.SECURITY_PRINCIPAL, "");
    env.put(Context.SECURITY_CREDENTIALS, "");
    String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(edit.getEid()) + "))";
    return getUserInf(edit, filter);
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {//from w  w  w.  ja va2 s  .  c  o  m
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    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);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

private boolean bindUser(DirContext context, String dn, String password) throws NamingException {
    boolean isValid = false;
    context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
    context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
    try {// ww w  . j a  va  2  s  .c o  m
        context.getAttributes("", null);
        isValid = true;
    } catch (AuthenticationException e) {
    }
    if (StringUtils.isNotEmpty(this.username)) {
        context.addToEnvironment(Context.SECURITY_PRINCIPAL, this.username);
    } else {
        context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
    }
    if (StringUtils.isNotEmpty(this.password)) {
        context.addToEnvironment(Context.SECURITY_CREDENTIALS, this.password);
    } else {
        context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
    }
    return isValid;
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testUserMethod() throws Exception {
    log.debug("+++ testUserMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.userMethod(info);/*from w w w.j  ava2  s .  c om*/
    bean.remove();
}

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

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer/*from   w w  w .  ja va  2 s . co  m*/
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        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, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            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 {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                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(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}

From source file:org.apache.axis2.transport.jms.JMSEndpoint.java

/**
 * Get the EPR for the given JMS connection factory and destination
 * the form of the URL is/*from   w  ww  . j  a  v  a  2  s . co  m*/
 * jms:/<destination>?[<key>=<value>&]*
 * Credentials Context.SECURITY_PRINCIPAL, Context.SECURITY_CREDENTIALS
 * JMSConstants.PARAM_JMS_USERNAME and JMSConstants.PARAM_JMS_USERNAME are filtered
 *
 * @return the EPR as a String
 */
private String getEPR() {
    StringBuffer sb = new StringBuffer();

    sb.append(JMSConstants.JMS_PREFIX).append(jndiDestinationName);
    sb.append("?").append(JMSConstants.PARAM_DEST_TYPE).append("=")
            .append(destinationType == JMSConstants.TOPIC ? JMSConstants.DESTINATION_TYPE_TOPIC
                    : JMSConstants.DESTINATION_TYPE_QUEUE);

    if (contentTypeRuleSet != null) {
        String contentTypeProperty = contentTypeRuleSet.getDefaultContentTypeProperty();
        if (contentTypeProperty != null) {
            sb.append("&");
            sb.append(JMSConstants.CONTENT_TYPE_PROPERTY_PARAM);
            sb.append("=");
            sb.append(contentTypeProperty);
        }
    }

    for (Map.Entry<String, String> entry : cf.getParameters().entrySet()) {
        if (!Context.SECURITY_PRINCIPAL.equalsIgnoreCase(entry.getKey())
                && !Context.SECURITY_CREDENTIALS.equalsIgnoreCase(entry.getKey())
                && !JMSConstants.PARAM_JMS_USERNAME.equalsIgnoreCase(entry.getKey())
                && !JMSConstants.PARAM_JMS_PASSWORD.equalsIgnoreCase(entry.getKey())) {
            sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
    }
    return sb.toString();
}

From source file:CreateJavaSchema.java

/**
 * Signs on to directory server using parameters supplied to program.
 * @return The initial context to the server.
 *//*from ww  w  .  ja  v  a  2 s  .  c o 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);
}