List of usage examples for javax.naming Context SECURITY_PRINCIPAL
String SECURITY_PRINCIPAL
To view the source code for javax.naming Context SECURITY_PRINCIPAL.
Click Source Link
From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java
protected void bindUser(DirContext context, String dn) throws NamingException, FailedLoginException { context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn); try {//from w w w . j a va 2 s . c o m context.getAttributes("", null); } catch (AuthenticationException e) { log.debug("Authentication failed for dn=" + dn); throw new FailedLoginException(); } finally { if (connectionUsername != null) { context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionUsername); } else { context.removeFromEnvironment(Context.SECURITY_PRINCIPAL); } if (connectionPassword != null) { context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword); } else { context.removeFromEnvironment(Context.SECURITY_CREDENTIALS); } } }
From source file:ru.efo.security.ADUserDetailsService.java
private DirContext getDirContext(String username, String password) throws NamingException { final Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.SECURITY_AUTHENTICATION, "simple"); props.put(Context.SECURITY_PRINCIPAL, username); props.put(Context.SECURITY_CREDENTIALS, password); props.put(Context.PROVIDER_URL, ldapUrl); props.put("java.naming.ldap.attributes.binary", "objectSID"); return new InitialDirContext(props); }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Get next free uidNumber.//from w ww . j a v a 2 s. c o m * * @return next free uidNumber */ private String getNextUidNumber() { 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; String rueckgabe = ""; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId")); Attribute la = attrs.get("uidNumber"); rueckgabe = (String) la.get(0); ctx.close(); } catch (NamingException e) { logger.error(e); Helper.setFehlerMeldung(e.getMessage()); } return rueckgabe; }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java
protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize, final AuthenticationDiagnostic diagnostic) throws AuthenticationException { final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic : new AuthenticationDiagnostic(); final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL); final String providerURL = config.get(Context.PROVIDER_URL); if (this.isSSLSocketFactoryRequired(config)) { final KeyStore trustStore = this.initTrustStore(); ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore); config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName()); }//from w ww .j av a 2 s .co m try { // If a page size has been requested, use LDAP v3 paging if (pageSize > 0) { final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null); ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) }); return ctx; } else { final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config)); final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); return ret; } } catch (final javax.naming.AuthenticationException ax) { final Object[] args1 = { securityPrincipal }; final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1); // wrong user/password - if we get this far the connection is O.K final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax); } catch (final CommunicationException ce) { final Object[] args1 = { providerURL }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1); final StringBuffer message = new StringBuffer(); message.append(ce.getClass().getName() + ", " + ce.getMessage()); Throwable cause = ce.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect final Object[] args = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce); } catch (final NamingException nx) { final Object[] args = { providerURL }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args); final StringBuffer message = new StringBuffer(); message.append(nx.getClass().getName() + ", " + nx.getMessage()); Throwable cause = nx.getCause(); while (cause != null) { message.append(", "); message.append(cause.getClass().getName() + ", " + cause.getMessage()); cause = cause.getCause(); } // failed to connect final Object[] args1 = { providerURL, message.toString() }; throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx); } catch (final IOException e) { final Object[] args = { providerURL, securityPrincipal }; effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args); throw new AuthenticationException("Unable to encode LDAP v3 request controls", e); } }
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Bind authenticate.//from ww w . jav a 2s . c om * * @param username the user to be used * @param password the password to be used * @return true if the user was authenticated * @throws PortalServiceException for any errors encountered */ public boolean authenticate(String username, String password) throws PortalServiceException { DirContext ctx = null; try { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, env.getProperty(Context.INITIAL_CONTEXT_FACTORY)); props.put(Context.PROVIDER_URL, env.getProperty(Context.PROVIDER_URL)); props.put(Context.SECURITY_PRINCIPAL, MessageFormat.format(userDNPattern, username)); props.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialDirContext(props); return true; } catch (AuthenticationException authEx) { return false; } catch (NamingException e) { throw new PortalServiceException("Could not verify authentication results.", e); } finally { closeContext(ctx); } }
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.LdapSaslSecurityRealm.java
/** * Authorize a user.//from w w w. j a v a2 s . c o m * * @param username * @param password * @see hudson.security.AbstractPasswordBasedSecurityRealm#authenticate(java.lang.String, java.lang.String) */ @Override protected UserDetails authenticate(String username, String password) throws AuthenticationException { Logger logger = getLogger(); // check configuration. String ldapUris = getValidLdapUris(); if (StringUtils.isBlank(ldapUris)) { logger.severe("No valid LDAP URI is specified."); throw new AuthenticationServiceException("No valid LDAP URI is specified."); } String mechanisms = getMechanisms(); if (StringUtils.isBlank(mechanisms)) { logger.severe("No valid mechanism is specified."); throw new AuthenticationServiceException("No valid mechanism is specified."); } // TODO: Test with LDAPS. // Parameters for JNDI Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUris); env.put(Context.SECURITY_PRINCIPAL, username); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.SECURITY_AUTHENTICATION, mechanisms); env.put("com.sun.jndi.ldap.connect.timeout", Integer.toString(getConnectionTimeout())); env.put("com.sun.jndi.ldap.read.timeout", Integer.toString(getReadTimeout())); logger.fine("Authenticating with LDAP-SASL:"); logger.fine(String.format("username=%s", username)); logger.fine(String.format("servers=%s", ldapUris)); logger.fine(String.format("mech=%s", mechanisms)); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); } catch (javax.naming.AuthenticationException e) { // Authentication Failure... throw new BadCredentialsException(String.format("Authentication failed: %s", username), e); } catch (NamingException e) { // Unexpected failure... throw new AuthenticationServiceException(String.format("Authentication failed: %s", username), e); } String userDn = (getUserDnResolver() != null) ? getUserDnResolver().getUserDn(ctx, username) : null; logger.fine(String.format("User DN is %s", userDn)); List<GrantedAuthority> authorities = (getGroupResolver() != null) ? getGroupResolver().resolveGroup(ctx, userDn, username) : new ArrayList<GrantedAuthority>(); logger.fine("Authenticating succeeded."); return new LdapUser(username, "", // password(not used) userDn, // dn of this user. true, // enabled true, // accountNonExpired true, // credentialsNonExpired true, // accountNonLocked authorities.toArray(new GrantedAuthority[0])); }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private DirContext connect(Config config) { try {/* www . j a va2 s . c o m*/ Properties env = new Properties(); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, config.getBindDN()); env.put(Context.SECURITY_CREDENTIALS, config.getPassword()); env.put(LDAP_VERSION, DEFAULT_LDAP_VERSION); env.put(Context.INITIAL_CONTEXT_FACTORY, DEFAULT_CTX); env.put(Context.PROVIDER_URL, "ldap://" + config.getHost() + ":" + config.getPort()); if (config.getReferral() != null) { env.put(Context.REFERRAL, config.getReferral()); } if (config.getProtocol() != null) env.put(Context.SECURITY_PROTOCOL, config.getProtocol()); env.put("com.sun.jndi.ldap.connect.pool", "true"); return new InitialDirContext(env); } catch (NamingException e) { throw new OXFException("LDAP connect Failed", e); } }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
/** * @throws NamingException//w ww .j av a 2s . c om * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String) */ protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) { Set<Map<String, String>> ret = new HashSet<Map<String, String>>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; } // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/ // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); boolean ldapApiEnumerationBugEncountered = false; while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change // We use the first match SearchResult si = null; try { si = answer.next(); } catch (NullPointerException npe) { ldapApiEnumerationBugEncountered = true; break; } Map<String, String> entry = new HashMap<String, String>(); String name = (String) si.getAttributes().get("cn").get(); name = name.trim(); Attribute desc = si.getAttributes().get("description"); String description = desc != null ? (String) desc.get() : ""; description = description.trim(); entry.put("id", name); entry.put("name", name); entry.put("description", description); ret.add(entry); } } } catch (NamingException e) { if (e instanceof InvalidSearchFilterException) { InvalidSearchFilterException fException = (InvalidSearchFilterException) e; String message = "The ldap group filter defined is invalid "; log.error(message, fException); throw new LdapFilterException(message + " " + fException.getMessage()); } //TODO: check for ldap connection/unavailable/etc. exceptions. else { log.error("LDAP communication error: " + e.getMessage(), e); throw new LdapCommunicationException(e); } } return ret; }
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 * //from ww w .j a va 2s .c o 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:de.sub.goobi.helper.ldap.Ldap.java
/** * Set next free uidNumber./*from ww w .j a v a 2s . c om*/ */ private void setNextUidNumber() { 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; try { ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId")); Attribute la = attrs.get("uidNumber"); String oldValue = (String) la.get(0); int bla = Integer.parseInt(oldValue) + 1; BasicAttribute attrNeu = new BasicAttribute("uidNumber", String.valueOf(bla)); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attrNeu); ctx.modifyAttributes(ConfigCore.getParameter("ldap_nextFreeUnixId"), mods); ctx.close(); } catch (NamingException e) { logger.error(e); } }