List of usage examples for javax.naming.directory DirContext getAttributes
public Attributes getAttributes(String name, String[] attrIds) throws NamingException;
From source file:it.infn.ct.security.utilities.LDAPUtils.java
private static boolean toggleUserIDPGroup(String cn, boolean activate) { ResourceBundle rb = ResourceBundle.getBundle("ldap"); String userDN = "cn=" + cn + "," + rb.getString("peopleRoot"); String idpUser = rb.getString("usersGroup"); DirContext ctx = null; try {//from w w w . j a v a 2 s .c om ctx = getMainAuthContext(); ModificationItem modAttrs[] = new ModificationItem[1]; String attrsList[] = { "uniqueMember" }; Attributes attributes = ctx.getAttributes(idpUser, attrsList); Attribute att = attributes.get("uniqueMember"); if (activate) { att.add(userDN); } else { att.remove(userDN); } modAttrs[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, att); ctx.modifyAttributes(idpUser, modAttrs); return true; } catch (NamingException ex) { _log.error(ex); } return false; }
From source file:de.interseroh.report.test.security.LdapServerTest.java
@Test public void testJndiSun() throws NamingException { Hashtable<String, String> contextParams = new Hashtable<String, String>(); contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389"); contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP); contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP); contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); DirContext dirContext = new InitialDirContext(contextParams); Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" }); Attribute attribute = attributes.get("namingContexts"); NamingEnumeration<?> all = attribute.getAll(); while (all.hasMore()) { String next = (String) all.next(); logger.info(next);//from w w w. j a v a2 s. c o m } }
From source file:sk.lazyman.gizmo.security.SimpleBindAunthenticator.java
private DirContextOperations bindWithDn(String userDnStr, String username, String password) { BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource(); DistinguishedName userDn = new DistinguishedName(userDnStr); DistinguishedName fullDn = new DistinguishedName(userDn); fullDn.prepend(ctxSource.getBaseLdapPath()); LOG.debug("Attempting to bind as " + fullDn); DirContext ctx = null;//from www . j a v a 2 s . c om try { ctx = getContextSource().getContext(fullDn.toString(), password); // Check for password policy control PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx); LOG.debug("Retrieving attributes..."); DirContext readOnlyCtx = getContextSource().getReadOnlyContext(); Attributes attrs = readOnlyCtx.getAttributes(userDn, getUserAttributes()); DirContextAdapter result = new DirContextAdapter(attrs, userDn, ctxSource.getBaseLdapPath()); if (ppolicy != null) { result.setAttributeValue(ppolicy.getID(), ppolicy); } return result; } catch (NamingException e) { // This will be thrown if an invalid user name is used and the method may // be called multiple times to try different names, so we trap the exception // unless a subclass wishes to implement more specialized behaviour. if ((e instanceof org.springframework.ldap.AuthenticationException) || (e instanceof org.springframework.ldap.OperationNotSupportedException)) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to bind as " + userDn + ": " + e); } } else { throw e; } } catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } finally { LdapUtils.closeContext(ctx); } return null; }
From source file:info.globalbus.dkim.DKIMUtil.java
public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); String recordname = selector + "._domainkey." + signingDomain; String value = null;/*from ww w .j av a 2 s . c o m*/ try { DirContext dnsContext = new InitialDirContext(env); javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname, new String[] { "TXT" }); javax.naming.directory.Attribute txtrecord = attribs.get("txt"); if (txtrecord == null) { throw new DKIMSignerException("There is no TXT record available for " + recordname); } // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..." value = (String) txtrecord.get(); } catch (NamingException ne) { throw new DKIMSignerException("Selector lookup failed", ne); } if (value == null) { throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved"); } // try to read public key from RR String[] tags = value.split(";"); for (String tag : tags) { tag = tag.trim(); if (tag.startsWith("p=")) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // decode public key, FSTODO: convert to DER format PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes()); keyFactory.generatePublic(pubSpec); } catch (NoSuchAlgorithmException nsae) { throw new DKIMSignerException("RSA algorithm not found by JVM"); } catch (InvalidKeySpecException ikse) { throw new DKIMSignerException( "The public key " + tag + " in RR " + recordname + " couldn't be decoded."); } // FSTODO: create test signature with privKey and test // validation with pubKey to check on a valid key pair return true; } } throw new DKIMSignerException("No public key available in " + recordname); }
From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java
public Attributes loadUser(String uid, String[] attrs) { // Preparar las variables de entorno para la conexin JNDI Hashtable<String, String> entorno = new Hashtable<String, String>(); // Credenciales del usuario para realizar la bsqueda String cadena = "uid=" + user + "," + context; entorno.put(Context.PROVIDER_URL, server); entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext); if (password != null && user != null) { entorno.put(Context.SECURITY_PRINCIPAL, cadena); entorno.put(Context.SECURITY_CREDENTIALS, password); }/*from w w w. jav a 2 s .c o m*/ Attributes atributos = null; try { // Crear contexto de directorio inicial DirContext ctx = new InitialDirContext(entorno); // Recuperar atributos del usuario que se est buscando if (attrs != null) atributos = ctx.getAttributes("uid=" + uid + "," + context, attrs); else atributos = ctx.getAttributes("uid=" + uid + "," + context); // Cerrar la conexion ctx.close(); } catch (NamingException e) { logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault())); } return atributos; }
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 {//from ww w . java 2 s .co 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:ru.efo.security.ADUserDetailsService.java
private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles) throws NamingException { if (memberOf != null) { for (int i = 0; i < memberOf.size(); i++) { Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN"); if (attr != null) { final String role = attr.get().toString(); if (rolesMapping != null) { for (String key : rolesMapping.keySet()) { if (role.matches(rolesMapping.get(key))) { if (logger.isLoggable(Level.FINE)) { if (!roles.contains(key)) { logger.log(Level.FINE, "Role: " + key); }// w w w. j a v a 2 s . c o m } roles.add(key); } } } else { final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix) + role.toUpperCase().replaceAll("(\\s|-)+", "_"); if (logger.isLoggable(Level.FINE)) { if (!roles.contains(role)) { logger.log(Level.FINE, "Role: " + roleWithPrefix); } } roles.add(roleWithPrefix); } groups.add(role); if (recursiveRoleSearch) { SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search( groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")", controls); if (renum.hasMore()) { SearchResult searchResult = renum.next(); attr = searchResult.getAttributes().get("memberOf"); describeRoles(context, attr, groups, roles); } } } } } }
From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java
private String getAttributes(DirContext oDirContext, String sMapperAttribute, Name name) throws OAException { String sReturn = null;//from w w w . j av a 2 s . com try { if (sMapperAttribute == null) { _logger.error("No attribute name to map to supplied"); throw new OAException(SystemErrors.ERROR_INTERNAL); } Attributes attributes = null; try { attributes = oDirContext.getAttributes(name, new String[] { sMapperAttribute }); } catch (InvalidSearchFilterException e) { StringBuffer sbFailed = new StringBuffer("Could not resolve attribute '"); sbFailed.append(sMapperAttribute); sbFailed.append("' while retrieving attributes for id: "); sbFailed.append(name); _logger.error(sbFailed.toString(), e); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } Attribute attrMapping = attributes.get(sMapperAttribute); if (attrMapping == null) { _logger.debug("Attribute not found: " + sMapperAttribute); } else { Object oValue = attrMapping.get(); if (!(oValue instanceof String)) { StringBuffer sbError = new StringBuffer("Returned value for attribute '"); sbError.append(sMapperAttribute); sbError.append("' has a value which is not of type 'String'"); _logger.error(sbError.toString()); throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE); } sReturn = (String) oValue; } } catch (OAException e) { throw e; } catch (NamingException e) { _logger.debug("Failed to fetch mapping attribute for id: " + name); } catch (Exception e) { _logger.fatal("Could not retrieve fields for id: " + name, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sReturn; }
From source file:CreateJavaSchema.java
/** * Locates the Active Directory schema./* w ww . ja va 2 s . c o m*/ * @return A context for the root of the Active Directory schema. */ private DirContext getADSchema(DirContext rootCtx) throws NamingException { System.out.println(" [locating the schema]"); String snc = "schemaNamingContext"; // DSE attribute Attributes attrs = rootCtx.getAttributes("", new String[] { snc }); return (DirContext) rootCtx.lookup((String) attrs.get(snc).get()); }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Resolves all the groups that the user is in. * * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a> * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in. * We then use that to retrieve all the groups in one query and resolve their canonical names. * * @param userDN//from w ww. jav a 2 s. c o m * User's distinguished name. * @param context Used for making queries. */ private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context) throws NamingException { if (userDN.contains("/")) { userDN = userDN.replace("/", "\\/"); } Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>(); LOGGER.log(Level.FINER, "Looking up group of {0}", userDN); Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" }); Attribute tga = id.get("tokenGroups"); if (tga == null) { // tga will be null if you are not using a global catalogue // or if the user is not actually a member of any security groups. LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN); // keep on trucking as we can still use memberOf for Distribution Groups. } else { // build up the query to retrieve all the groups StringBuilder query = new StringBuilder("(|"); List<byte[]> sids = new ArrayList<byte[]>(); NamingEnumeration<?> tokenGroups = tga.getAll(); while (tokenGroups.hasMore()) { byte[] gsid = (byte[]) tokenGroups.next(); query.append("(objectSid={" + sids.size() + "})"); sids.add(gsid); } tokenGroups.close(); query.append(")"); NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search(query.toString(), sids.toArray()); parseMembers(userDN, groups, renum); renum.close(); } {/* stage 2: use memberOf to find groups that aren't picked up by tokenGroups. This includes distribution groups */ LOGGER.fine("Stage 2: looking up via memberOf"); while (true) { switch (groupLookupStrategy) { case TOKENGROUPS: // no extra lookup - ever. return groups; case AUTO: // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster long start = System.nanoTime(); boolean found = false; long duration = 0; try { found = chainGroupLookup(domainDN, userDN, context, groups); duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start); } catch (TimeLimitExceededException e) { LOGGER.log(Level.WARNING, "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup", e); } catch (NamingException e) { if (e.getMessage().contains("LDAP response read timed out")) { LOGGER.log(Level.WARNING, "LDAP response read time out. AD will fall back to recursive lookup", e); } else { throw e; } } if (!found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else if (found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; return groups; } else if (!found) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries"); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else { // it run fast enough, so let's stick to it groupLookupStrategy = GroupLookupStrategy.CHAIN; return groups; } case RECURSIVE: recursiveGroupLookup(context, id, groups); return groups; case CHAIN: chainGroupLookup(domainDN, userDN, context, groups); return groups; } } } }