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:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * /*w  w  w.ja  v a 2 s . co m*/
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

From source file:org.webterm.core.plugin.authentication.LdapAuthentication.java

@Override
public void init() {
    LOG.info("Initializing LDAP authentication..."); //$NON-NLS-1$

    try {/*from   w  ww.j  a  v  a 2  s  .  c o m*/
        final ConfigurationReader config = ConfigurationReader.getInstance();
        final String serverName = config.getApplicationProperty(CONFIG_SERVER_NAME);
        final String serverPort = config.getApplicationProperty(CONFIG_SERVER_PORT);
        final String bindDn = config.getApplicationProperty(CONFIG_BIND_DN);
        final String bindPwd = config.getApplicationProperty(CONFIG_BIND_PWD);
        this.baseDn = config.getApplicationProperty(CONFIG_BASE_DN);
        this.attrUser = config.getApplicationProperty(CONFIG_ATTR_USER);
        this.attrPwd = config.getApplicationProperty(CONFIG_ATTR_PWD);
        this.checkMethode = this.map.get(config.getApplicationProperty(CONFIG_PASSWORD_ENCODE));
        if (this.checkMethode == null) {
            LOG.fatal("unknown method: " + config.getApplicationProperty(CONFIG_PASSWORD_ENCODE)); //$NON-NLS-1$
        }

        final Hashtable<String, String> ldapEnv = new Hashtable<String, String>(); // NOPMD - HashTable is needed
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
        ldapEnv.put(Context.PROVIDER_URL, "ldap://" + serverName + ":" + serverPort); //$NON-NLS-1$ //$NON-NLS-2$
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");//$NON-NLS-1$
        ldapEnv.put(Context.SECURITY_PRINCIPAL, bindDn);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, bindPwd);
        this.ldapContext = new InitialDirContext(ldapEnv);
    } catch (Exception ex) {
        LOG.error(ex, ex);
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
LDAPConnectionContext(Map<String, String> userStoreProperties) throws UserStoreException {

    String connectionURL = userStoreProperties.get(LDAPConstants.CONNECTION_URL);
    String connectionName = userStoreProperties.get(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = userStoreProperties.get(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }/*  w  w  w  . j  a  v a 2 s  .com*/

    environment = new Hashtable<>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (connectionName != null) {
        environment.put(Context.SECURITY_PRINCIPAL, connectionName);
    }

    if (connectionPassword != null) {
        environment.put(Context.SECURITY_CREDENTIALS, connectionPassword);
    }

    if (connectionURL != null) {
        environment.put(Context.PROVIDER_URL, connectionURL);
    }

    // Enable connection pooling if property is set in user-mgt.xml
    boolean isLDAPConnectionPoolingEnabled = false;
    String value = userStoreProperties.get(LDAPConstants.CONNECTION_POOLING_ENABLED);

    if (value != null && !value.trim().isEmpty()) {
        isLDAPConnectionPoolingEnabled = Boolean.parseBoolean(value);
    }

    environment.put("com.sun.jndi.ldap.connect.pool", isLDAPConnectionPoolingEnabled ? "true" : "false");

    // set referral status if provided in configuration.
    if (userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral", userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL));
    }
    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = userStoreProperties.get(CONNECTION_TIME_OUT);
    String readTimeout = userStoreProperties.get(READ_TIME_OUT);
    if (connectTimeout != null && !connectTimeout.trim().isEmpty()) {
        environment.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    } else {
        environment.put("com.sun.jndi.ldap.connect.timeout", "5000");
    }

    if (StringUtils.isNotEmpty(readTimeout)) {
        environment.put("com.sun.jndi.ldap.read.timeout", readTimeout);
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
public LDAPConnectionContext(RealmConfiguration realmConfig) throws UserStoreException {

    //if DNS is enabled, populate DC Map
    String DNSUrl = realmConfig.getUserStoreProperty(LDAPConstants.DNS_URL);
    if (DNSUrl != null) {
        DNSDomainName = realmConfig.getUserStoreProperty(LDAPConstants.DNS_DOMAIN_NAME);
        if (DNSDomainName == null) {
            throw new UserStoreException("DNS is enabled, but DNS domain name not provided.");
        } else {/*from w  ww. j  av a  2 s . com*/
            environmentForDNS = new Hashtable();
            environmentForDNS.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            environmentForDNS.put("java.naming.provider.url", DNSUrl);
            populateDCMap();
        }
        //need to keep track of if the user store config is read only
        String readOnlyString = realmConfig
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY);
        if (readOnlyString != null) {
            readOnly = Boolean.parseBoolean(readOnlyString);
        }
    }

    String rawConnectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
    String connectionURL = null;
    //if DNS enabled in AD case, this can be null
    if (rawConnectionURL != null) {
        String portInfo = rawConnectionURL.split(":")[2];

        String port = null;

        // if the port contains a template string that refers to carbon.xml
        if ((portInfo.contains("${")) && (portInfo.contains("}"))) {
            port = Integer.toString(CarbonUtils.getPortFromServerConfig(portInfo));
        }

        if (port != null) {
            connectionURL = rawConnectionURL.replace(portInfo, port);
        } else {
            // if embedded-ldap is not enabled,
            connectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
        }
    }

    String connectionName = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }

    environment = new Hashtable();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    /**
     * In carbon JNDI context we need to by pass specific tenant context and we need the base
     * context for LDAP operations.
     */
    environment.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");

    if (connectionName != null) {
        environment.put(Context.SECURITY_PRINCIPAL, connectionName);
    }

    if (connectionPassword != null) {
        environment.put(Context.SECURITY_CREDENTIALS, connectionPassword);
    }

    if (connectionURL != null) {
        environment.put(Context.PROVIDER_URL, connectionURL);
    }

    // Enable connection pooling if property is set in user-mgt.xml
    boolean isLDAPConnectionPoolingEnabled = false;
    String value = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_POOLING_ENABLED);

    if (value != null && !value.trim().isEmpty()) {
        isLDAPConnectionPoolingEnabled = Boolean.parseBoolean(value);
    }

    environment.put("com.sun.jndi.ldap.connect.pool", isLDAPConnectionPoolingEnabled ? "true" : "false");

    // set referral status if provided in configuration.
    if (realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral",
                realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL));
    }

    String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY);

    if (binaryAttribute != null) {
        environment.put(LDAPConstants.LDAP_ATTRIBUTES_BINARY, binaryAttribute);
    }

    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = realmConfig.getUserStoreProperty(CONNECTION_TIME_OUT);
    if (connectTimeout != null && !connectTimeout.trim().isEmpty()) {
        environment.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    } else {
        environment.put("com.sun.jndi.ldap.connect.timeout", "5000");
    }
}

From source file:se.vgregion.service.barium.BariumRestClientIT.java

License:asdf

public static void main(String[] args) {

    try {//from   ww  w.  jav  a  2  s.  c om
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "LDAP://my.ldap.server:389"); //replace with your server URL/IP
        //only DIGEST-MD5 works with our Windows Active Directory
        env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5"); //No other SALS worked with me
        env.put(Context.SECURITY_PRINCIPAL, "user1"); // specify the username ONLY to let Microsoft Happy
        env.put(Context.SECURITY_CREDENTIALS, "secret1"); //the password

        DirContext ctx = new InitialDirContext(env);

        ctx.close();

    } catch (NamingException ne) {
        System.out.println("Error authenticating user:");
        System.out.println(ne.getMessage());
        return;
    }

    //if no exception, the user is already authenticated.
    System.out.println("OK, successfully authenticating user");
}

From source file:xc.mst.manager.user.DefaultUserService.java

/**
 * Creates a connection to the LDAP server based on values defined in the configuration file.
 * This method logs into the server with a specified username and password
 * /*  ww w  .j av a 2  s . com*/
 * @param username
 *            The username to log into the LDAP server
 * @param password
 *            The password to log into the LDAP server
 * @return A connection to the LDAP server defined in the configuration file.
 * @throws ILSException
 *             if the username and password were wrong or we couldn't find the LDAP server
 */
private static DirContext getLDAPConnection(String username, String password, Server loginserver) {

    Properties ldapProperties = getGenericLDAPProperties(loginserver);
    try {
        // Set up the environment for creating the initial context

        // Get the username attribute and start location on the LDAP server from the configuration file
        String usernameAttribute = loginserver.getUserNameAttribute();
        String startLocation = loginserver.getStartLocation();

        // Set up the properties to authenticate with the correct username and password
        // The username passed to this function will be something like "jsmith", but we
        // need to authenticate to the correct LDAP location using the provided parameter.
        // For this reason we pull the username attribute at start locations from the
        // configuration file. The result will be setting the SECURITY_PRINCIPAL (LDAP username)
        // to something like "uid=jsmith, ou=people, dc=rochester, dc=edu"
        ldapProperties.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); // Set this property because we will be authenticating
        ldapProperties.setProperty(Context.SECURITY_PRINCIPAL,
                usernameAttribute + "=" + username + ", " + startLocation);
        ldapProperties.setProperty(Context.SECURITY_CREDENTIALS, password);

        // Get the environment properties (props) for creating initial
        // context and specifying LDAP service provider parameters.
        return new InitialDirContext(ldapProperties);
    }
    // catch(MalformedURLException e1) {} // not thrown in above, but I thought I saw this in the log with misconfigured ldap?
    // catch(AuthenticationException e2) {} // more specific then below, I think this is the one thrown if invalid password.
    catch (NamingException e) {
        // If the exception was an error code 49, the username or password was incorrect.
        log.error(
                "Exception occured while authenticating user against LDAP server.If the exception was an error code 49, the username or password was incorrect",
                e);
        InitialDirContext in = null;
        return in;
    }
}