List of usage examples for javax.naming.ldap LdapName LdapName
public LdapName(List<Rdn> rdns)
From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java
public Map<String, String> parseDN(String dnString) throws InvalidNameException { Map<String, String> toReturn = new HashMap<>(); LdapName ldapName = new LdapName(dnString); if (log.isDebugEnabled()) { log.debug("Parsing DN: " + dnString); log.debug("ldapNames size:" + ldapName.size()); }//w w w. ja v a 2 s . co m for (Rdn rdn : ldapName.getRdns()) { if (rdn.getValue() instanceof String) { if (log.isDebugEnabled()) { log.debug("RDN: '" + rdn.getType() + "' has a String value"); } toReturn.put(rdn.getType(), (String) rdn.getValue()); } else if (rdn.getValue() instanceof byte[]) { if (log.isDebugEnabled()) { log.debug("RDN: '" + rdn.getType() + "' has a binary value"); } toReturn.put(rdn.getType(), new String((byte[]) rdn.getValue())); } } return toReturn; }
From source file:ldap.SearchUtility.java
/** * recursively walks the tree to depth 'depth', and returns * a list of all names found at that depth. * @param treeNode/*from www. ja v a2 s . c o m*/ * @param depth * @return * @throws NamingException */ private List<LdapName> getElementNames(LdapName treeNode, int depth, DirContext context) throws NamingException { depth--; NamingEnumeration<NameClassPair> children = context.list(treeNode); List<LdapName> elementNames = new ArrayList<LdapName>(); // cycle through all the children we've found. while (children.hasMore()) { NameClassPair child = children.next(); LdapName childName = new LdapName(child.getNameInNamespace()); if (depth == 0) // return value - these are what we're looking for! elementNames.add(childName); else elementNames.addAll(getElementNames(childName, depth, context)); // keep going down! } return elementNames; }
From source file:ldap.SearchUtility.java
/** * This returns a list of all users that match the particular attribute value. * Often this will be a single user, in which case the list will only contain one value. If * you know this is the case, use the 'getUser()' form of this method instead. * @param attrType//w ww . ja v a2 s. c o m * @param attrValue * @return * @throws NamingException */ public List<Entry> getUsers(String attrType, String attrValue, DirContext context) throws NamingException { logger.info("getUsers(attrType,attrValue,context)"); List<Entry> users = new ArrayList<Entry>(); Attributes atts = new BasicAttributes(); atts.put(attrType, attrValue); //NamingEnumeration<SearchResult> userResults = context.search(new LdapName(Config.SEARCH_BASE_DN), attrType + "={0}", new String[] {attrValue}, getSearchControls()); NamingEnumeration<SearchResult> userResults = context.search(new LdapName(LdapConstants.ldapSearchBaseDn), attrType + "={0}", new String[] { attrValue }, getSearchControls()); while (userResults.hasMore()) { SearchResult userResult = userResults.next(); users.add(new Entry(userResult)); } return users; }
From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java
protected static Name createName(String name) throws InvalidNameException { return new LdapName(name); }
From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java
/** * Parse an LDAP name//ww w. ja v a 2 s . co m * @param name the LDAP string * @return map of LDAP type/value */ private static Map<String, String> parseLdapName(String name) { Map<String, String> rdns = new HashMap<String, String>(); try { LdapName ldapName = new LdapName(name); for (Rdn rdn : ldapName.getRdns()) { rdns.put(rdn.getType(), rdn.getValue().toString()); } } catch (InvalidNameException e) { LOG.error("Error parsing the issuer name " + name, e); } return rdns; }
From source file:ldap.SearchUtility.java
public boolean userHasAttribute(String DN, String attrType, String attrValue, DirContext context) throws NamingException { Attributes atts = new BasicAttributes(); atts.put(attrType, attrValue);/* ww w . jav a 2s . com*/ NamingEnumeration<SearchResult> userResults = context.search(new LdapName(DN), "(" + attrType + "={0})", new String[] { attrValue }, getSearchControls()); return (userResults.hasMore()); }
From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java
private List<String> getResourceList(PortletSession session, String DN) throws InvalidNameException { logger.trace("getResourceList"); List<Middleware> pResources = (List<Middleware>) session.getAttribute("resources", session.APPLICATION_SCOPE);/*from ww w . ja va 2 s . com*/ if (pResources == null) { return null; } List<String> Names = new Vector<String>(); boolean flag = false; LdapName name = new LdapName(DN); logger.info("Comparing LDAP name " + name.toString()); for (Middleware t : pResources) { flag = false; if (t.isEnabled()) { for (Certificate c : t.getCertificate()) { if (Certificate.SAML.equals(c)) { flag = true; } } } if (flag) { for (Item i : t.getItem()) { Unicore uni = i.getUnicore(); if (t.isEnabled()) { try { LdapName subject = new LdapName(uni.getSubjectdn()); logger.info("Checking DN: " + uni.getSubjectdn() + "?"); logger.info("Subject: " + subject.toString()); if (name.equals(subject)) { Names.add(i.getName()); } } catch (InvalidNameException e) { logger.warn("Internal error: Reported certificate from service invalid" + uni); logger.warn("Reported DN: " + uni.getSubjectdn()); logger.debug("Stack trace:", e); } logger.debug("Alias" + uni.getKeyalias()); } } } } return Names; }
From source file:au.org.theark.core.service.ArkCommonServiceImpl.java
public ArkUserVO getUser(String username) throws ArkSystemException, EntityNotFoundException { ArkUserVO userVO = new ArkUserVO(); try {/*from ww w .j a v a 2 s . c om*/ LdapName ldapName = new LdapName(ldapDataContextSource.getBasePeopleDn()); ldapName.add(new Rdn("cn", username)); Name nameObj = (Name) ldapName; userVO = (ArkUserVO) ldapDataContextSource.getLdapTemplate().lookup(nameObj, new PersonContextMapper()); } catch (InvalidNameException ne) { throw new ArkSystemException("A System error has occured"); } catch (NameNotFoundException ex) { log.error(username + " not found in LDAP"); throw new EntityNotFoundException(); } return userVO; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Authenticates and retrieves the user by using the given list of available AD LDAP servers. * /* w ww .ja va2 s .c o m*/ * @param password * If this is {@link #NO_AUTHENTICATION}, the authentication is not performed, and just the retrieval * would happen. * @throws UsernameNotFoundException * The user didn't exist. * @return never null */ @SuppressFBWarnings(value = "ES_COMPARING_PARAMETER_STRING_WITH_EQ", justification = "Intentional instance check.") public UserDetails retrieveUser(final String username, final String password, final ActiveDirectoryDomain domain, final List<SocketInfo> ldapServers) { UserDetails userDetails; String hashKey = username + "@@" + DigestUtils.sha1Hex(password); final String bindName = domain.getBindName(); final String bindPassword = Secret.toString(domain.getBindPassword()); try { final ActiveDirectoryUserDetail[] cacheMiss = new ActiveDirectoryUserDetail[1]; userDetails = userCache.get(hashKey, new Callable<UserDetails>() { public UserDetails call() throws AuthenticationException { DirContext context; boolean anonymousBind = false; // did we bind anonymously? // LDAP treats empty password as anonymous bind, so we need to reject it if (StringUtils.isEmpty(password)) { throw new BadCredentialsException("Empty password"); } String userPrincipalName = getPrincipalName(username, domain.getName()); String samAccountName = userPrincipalName.substring(0, userPrincipalName.indexOf('@')); if (bindName != null) { // two step approach. Use a special credential to obtain DN for the // user trying to login, then authenticate. try { context = descriptor.bind(bindName, bindPassword, ldapServers, props); anonymousBind = false; } catch (BadCredentialsException e) { throw new AuthenticationServiceException( "Failed to bind to LDAP server with the bind name/password", e); } } else { if (password.equals(NO_AUTHENTICATION)) { anonymousBind = true; } try { // if we are just retrieving the user, try using anonymous bind by empty password (see RFC 2829 5.1) // but if that fails, that's not BadCredentialException but UserMayOrMayNotExistException context = descriptor.bind(userPrincipalName, anonymousBind ? "" : password, ldapServers, props); } catch (BadCredentialsException e) { if (anonymousBind) // in my observation, if we attempt an anonymous bind and AD doesn't allow it, it still passes the bind method // and only fail later when we actually do a query. So perhaps this is a dead path, but I'm leaving it here // anyway as a precaution. throw new UserMayOrMayNotExistException( "Unable to retrieve the user information without bind DN/password configured"); throw e; } } try { // locate this user's record final String domainDN = toDC(domain.getName()); Attributes user = new LDAPSearchBuilder(context, domainDN).subTreeScope() .searchOne("(& (userPrincipalName={0})(objectCategory=user))", userPrincipalName); if (user == null) { // failed to find it. Fall back to sAMAccountName. // see http://www.nabble.com/Re%3A-Hudson-AD-plug-in-td21428668.html LOGGER.log(Level.FINE, "Failed to find {0} in userPrincipalName. Trying sAMAccountName", userPrincipalName); user = new LDAPSearchBuilder(context, domainDN).subTreeScope() .searchOne("(& (sAMAccountName={0})(objectCategory=user))", samAccountName); if (user == null) { throw new UsernameNotFoundException( "Authentication was successful but cannot locate the user information for " + username); } } LOGGER.fine("Found user " + username + " : " + user); Object dnObject = user.get(DN_FORMATTED).get(); if (dnObject == null) { throw new AuthenticationServiceException("No distinguished name for " + username); } String dn = dnObject.toString(); LdapName ldapName = new LdapName(dn); String dnFormatted = ldapName.toString(); if (bindName != null && !password.equals(NO_AUTHENTICATION)) { // if we've used the credential specifically for the bind, we // need to verify the provided password to do authentication LOGGER.log(Level.FINE, "Attempting to validate password for DN={0}", dn); DirContext test = descriptor.bind(dnFormatted, password, ldapServers, props); // Binding alone is not enough to test the credential. Need to actually perform some query operation. // but if the authentication fails this throws an exception try { new LDAPSearchBuilder(test, domainDN).searchOne( "(& (userPrincipalName={0})(objectCategory=user))", userPrincipalName); } finally { closeQuietly(test); } } Set<GrantedAuthority> groups = resolveGroups(domainDN, dnFormatted, context); groups.add(SecurityRealm.AUTHENTICATED_AUTHORITY); cacheMiss[0] = new ActiveDirectoryUserDetail(username, password, true, true, true, true, groups.toArray(new GrantedAuthority[groups.size()]), getStringAttribute(user, "displayName"), getStringAttribute(user, "mail"), getStringAttribute(user, "telephoneNumber")); return cacheMiss[0]; } catch (NamingException e) { if (anonymousBind && e.getMessage().contains("successful bind must be completed") && e.getMessage().contains("000004DC")) { // sometimes (or always?) anonymous bind itself will succeed but the actual query will fail. // see JENKINS-12619. On my AD the error code is DSID-0C0906DC throw new UserMayOrMayNotExistException( "Unable to retrieve the user information without bind DN/password configured"); } LOGGER.log(Level.WARNING, String.format("Failed to retrieve user information for %s", username), e); throw new BadCredentialsException("Failed to retrieve user information for " + username, e); } finally { closeQuietly(context); } } }); if (cacheMiss[0] != null) { threadPoolExecutor.execute(new Runnable() { @Override public void run() { final String threadName = Thread.currentThread().getName(); Thread.currentThread() .setName(threadName + " updating-cache-for-user-" + cacheMiss[0].getUsername()); LOGGER.log(Level.FINEST, "Starting the cache update {0}", new Date()); try { long t0 = System.currentTimeMillis(); cacheMiss[0].updateUserInfo(); LOGGER.log(Level.FINEST, "Finished the cache update {0}", new Date()); long t1 = System.currentTimeMillis(); LOGGER.log(Level.FINE, "The cache for user {0} took {1} msec", new Object[] { cacheMiss[0].getUsername(), String.valueOf(t1 - t0) }); } finally { Thread.currentThread().setName(threadName); } } }); } } catch (UncheckedExecutionException e) { Throwable t = e.getCause(); if (t instanceof AuthenticationException) { AuthenticationException authenticationException = (AuthenticationException) t; throw authenticationException; } else { throw new CacheAuthenticationException( "Authentication failed because there was a problem caching user " + username, e); } } catch (ExecutionException e) { LOGGER.log(Level.SEVERE, "There was a problem caching user " + username, e); throw new CacheAuthenticationException( "Authentication failed because there was a problem caching user " + username, e); } // We need to check the password when the user is cached so it doesn't get automatically authenticated // without verifying the credentials if (password != null && !password.equals(NO_AUTHENTICATION) && userDetails != null && !password.equals(userDetails.getPassword())) { throw new BadCredentialsException("Failed to retrieve user information from the cache for " + username); } return userDetails; }
From source file:nu.yona.server.device.rest.DeviceController.java
@PostConstruct private void setSslRootCertificateCn() { try {//from ww w . j a v a 2 s . c o m LdapName name = new LdapName(sslRootCertificate.getIssuerX500Principal().getName()); DeviceResource.setSslRootCertificateCn(name.getRdn(0).getValue().toString()); } catch (InvalidNameException e) { throw YonaException.unexpected(e); } }