List of usage examples for javax.naming.ldap LdapName toString
public String toString()
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 www . ja v a 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:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java
private List<String> getResourceList(ActionRequest request, String DN) throws InvalidNameException { @SuppressWarnings("unchecked") List<Middleware> pResources = (List<Middleware>) request.getPortletSession().getAttribute("resources", request.getPortletSession().APPLICATION_SCOPE); List<String> Names = new Vector<String>(); boolean flag = false; LdapName name = new LdapName(DN); System.out.println("Comparing LDAP name " + name.toString()); for (Middleware t : pResources) { flag = false;//from w w w . j av a2 s. com 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()); System.out.println("Checking DN: " + uni.getSubjectdn() + "?"); System.out.println("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.trace("Stack trace:", e); } // System.out.println("uni-alias" + uni.getKeyalias()); } } } } return Names; }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Authenticates and retrieves the user by using the given list of available AD LDAP servers. * //from ww w . jav a 2 s . c om * @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:org.apache.zeppelin.realm.LdapRealm.java
boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl, final LdapContextFactory ldapContextFactory) throws NamingException { // ldap://host:port/dn?attributes?scope?filter?extensions if (memberUrl == null) { return false; }// w w w . j av a 2 s.c o m String[] tokens = memberUrl.split("\\?"); if (tokens.length < 4) { return false; } String searchBaseString = tokens[0].substring(tokens[0].lastIndexOf("/") + 1); String searchScope = tokens[2]; String searchFilter = tokens[3]; LdapName searchBaseDn = new LdapName(searchBaseString); // do scope test if (searchScope.equalsIgnoreCase("base")) { log.debug("DynamicGroup SearchScope base"); return false; } if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) { return false; } if (searchScope.equalsIgnoreCase("one") && (userLdapDn.size() != searchBaseDn.size() - 1)) { log.debug("DynamicGroup SearchScope one"); return false; } // search for the filter, substituting base with userDn // search for base_dn=userDn, scope=base, filter=filter LdapContext systemLdapCtx = null; systemLdapCtx = ldapContextFactory.getSystemLdapContext(); boolean member = false; NamingEnumeration<SearchResult> searchResultEnum = null; try { searchResultEnum = systemLdapCtx.search(userLdapDn, searchFilter, searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE : ONELEVEL_SCOPE); if (searchResultEnum.hasMore()) { return true; } } finally { try { if (searchResultEnum != null) { searchResultEnum.close(); } } finally { LdapUtils.closeContext(systemLdapCtx); } } return member; }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void grantRole(LdapUser user, String role) { try {//from www . ja va 2 s . co m LdapName rootDn = namingFactory.createUsersDn(user.getTenantId()); Rdn userRdn = NamingFactory.createRdn(RdnType.UID, user.getUserId()); LdapName userName = NamingFactory.createName(userRdn); boolean isUserExists = ldapDao.isRdnExists(rootDn, userName); if (!isUserExists) { throw new IllegalArgumentException(user + " does not exists"); } LdapName userDn = namingFactory.createUserDn(user.getTenantId(), user.getUserId()); LdapName roleDn = namingFactory.createRoleDn(user.getTenantId(), role); ldapDao.addRdn(roleDn, RdnType.UNIQUE_MEMBER, userDn.toString()); } catch (RuntimeException e) { log.error(e); throw new java.lang.RuntimeException(e); } }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void revokeRole(LdapUser user, String role) { try {/*from w ww . java 2s .c o m*/ LdapName userDn = namingFactory.createUserDn(user.getTenantId(), user.getUserId()); LdapName roleDn = namingFactory.createRoleDn(user.getTenantId(), role); ldapDao.removeRdn(roleDn, RdnType.UNIQUE_MEMBER, userDn.toString()); } catch (RuntimeException e) { log.error(e); throw e; } }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void deleteRole(String tenantId, String role) { try {//from w w w.jav a2 s.co m LdapName roleDn = namingFactory.createRoleDn(tenantId, role); LdapName rolesDn = namingFactory.createRolesDn(tenantId); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(RdnType.UNIQUE_MEMBER.toString(), roleDn)); List<String> grantedRoles = ldapDao.findRdnValues(rolesDn, attributes, RdnType.CN); for (String grantedRole : grantedRoles) { LdapName grantedRoleDn = namingFactory.createRoleDn(tenantId, grantedRole); ldapDao.removeRdn(roleDn, RdnType.UNIQUE_MEMBER, grantedRoleDn.toString()); } Rdn roleRdn = namingFactory.createRoleRdn(role); ldapDao.deleteSubContext(rolesDn, roleRdn); } catch (NamingException e) { log.error(e); throw new java.lang.RuntimeException(e); } }
From source file:org.easy.ldap.AdminServiceImpl.java
@Override public void revokeAllRoles(LdapUser user) { LdapName userDn = namingFactory.createUserDn(user.getTenantId(), user.getUserId()); LdapName rolesDn = namingFactory.createRolesDn(user.getTenantId()); Attributes attributes = new BasicAttributes(); attributes.put(new BasicAttribute(RdnType.UNIQUE_MEMBER.toString(), userDn)); List<String> grantedRoles = ldapDao.findRdnValues(rolesDn, attributes, RdnType.CN); for (String role : grantedRoles) { LdapName roleDn = namingFactory.createRoleDn(user.getTenantId(), role); ldapDao.removeRdn(roleDn, RdnType.UNIQUE_MEMBER, userDn.toString()); }// w ww.j a v a 2s.c o m }
From source file:org.easy.ldap.LdapContextFactory.java
public DirContext createSecureContext(LdapName rootDn, LdapName principal, String password, String securityMethod) throws NamingException { Hashtable<String, String> environment = getEnviroment(); environment.put(Context.PROVIDER_URL, createProviderUrl(rootDn.toString())); environment.put(Context.SECURITY_AUTHENTICATION, securityMethod); environment.put(Context.SECURITY_PRINCIPAL, principal.toString()); environment.put(Context.SECURITY_CREDENTIALS, password); return createContext(environment); }
From source file:org.easy.ldap.LdapDao.java
public void updateRdn(LdapName rootDn, RdnType type, String rdnValue) { DirContext ctx = null;/*from w w w. jav a2s. c o m*/ try { ctx = contextFactory.createContext(rootDn.toString()); ModificationItem[] modifications = new ModificationItem[1]; Attribute attribute = new BasicAttribute(type.toString(), rdnValue); modifications[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute); ctx.modifyAttributes("", modifications); } catch (NamingException e) { throw new RuntimeException(type.toString() + "=" + rdnValue + "," + rootDn.toString(), e); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { log.debug(e); } } } }