List of usage examples for javax.naming.directory DirContext modifyAttributes
public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException;
From source file:CreateJavaSchema.java
/** * Writes schema modifications to the Active Directory schema immediately. *//*from w w w . j a v a 2s . c om*/ protected void flushADSchemaMods(DirContext rootCtx) throws NamingException { rootCtx.modifyAttributes("", new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("schemaUpdateNow", "1")) }); }
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Updates the profile of the user on the external provider. * * @param user the profile to be updated (it is assumed username is never changed) * @throws PortalServiceException for any errors encountered *//*from w w w . j a v a 2 s. c om*/ public void updateUser(CMSUser user) throws PortalServiceException { DirContext ctx = null; try { ctx = new InitialDirContext(env); List<ModificationItem> mods = new ArrayList<ModificationItem>(); List<Attribute> profile = mapAttributes(user); for (Attribute attribute : profile) { mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute)); } ctx.modifyAttributes(MessageFormat.format(userDNPattern, user.getUsername()), mods.toArray(new ModificationItem[0])); synchRoles(user.getUsername(), user.getRole()); } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to save user.", e); } finally { closeContext(ctx); } }
From source file:org.archone.ad.domain.LdapActions.java
@RPCAction(name = "domain.create", required = { "domain", "userName", "password", "rootDn", "rootDnPassword" }) @RequiresRoles("SUPERUSER") public HashMap<String, Object> createDomain(OperationContext opContext) throws NamingException, NoSuchAlgorithmException, UnsupportedEncodingException { String domain = (String) opContext.getParams().get("domain"); String userName = (String) opContext.getParams().get("userName"); String password = (String) opContext.getParams().get("password"); String rootDn = (String) opContext.getParams().get("rootDn"); String rootDnPassword = (String) opContext.getParams().get("rootDnPassword"); DirContext dirContext = contextSource.getContext(rootDn, rootDnPassword); DirContextAdapter userRoot = (DirContextAdapter) dirContext .lookup("ds-cfg-backend-id=userRoot,cn=Backends,cn=config"); DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain); //Declaring backend userRoot.addAttributeValue("ds-cfg-base-dn", domainDn.toString()); dirContext.modifyAttributes(userRoot.getNameInNamespace(), userRoot.getModificationItems()); //Creating backend DirContextAdapter adapter = new DirContextAdapter(); adapter.setAttributeValues("objectclass", new String[] { "top", "domain" }); adapter.setAttributeValue("dc", domain.split("\\.")[0]); dirContext.bind(domainDn.toString(), adapter, null); //Creating group node DirContextAdapter groupNode = new DirContextAdapter(); groupNode.setAttributeValue("objectclass", "organizationalUnit"); dirContext.bind(domainDn.getGroupNodeDn(), groupNode); //creating user node DirContextAdapter userNode = new DirContextAdapter(); userNode.setAttributeValue("objectclass", "organizationalUnit"); dirContext.bind(domainDn.getUserNodeDn(), userNode); //creating user DirContextAdapter userAccount = new DirContextAdapter(); userAccount.setAttributeValues("objectclass", ldapConfiguration.getUserObjectClassList().toArray()); userAccount.setAttributeValue("sn", userName); userAccount.setAttributeValue("cn", userName); UserDn userDn = nameHelper.newUserDn(userName, domainDn); userAccount.setAttributeValue("userPassword", password); dirContext.bind(userDn, userAccount); //creating admin group DirContextAdapter adminGroup = new DirContextAdapter(); adminGroup.setAttributeValues("objectclass", ldapConfiguration.getGroupObjectClassList().toArray()); adminGroup.setAttributeValue("uniqueMember", userDn.toString()); GroupDn groupDn = nameHelper.newGroupDn("administrator", domainDn); dirContext.bind(groupDn, adminGroup); HashMap<String, Object> response = new HashMap<String, Object>(); response.put("success", true); return response; }
From source file:ca.tnt.ldaputils.impl.LdapEntry.java
/** * Runs the batch modifications requested through the {@link * ILdapEntry#modifyBatchAttribute(int, String, Object)} *//*from ww w . j ava 2 s . c o m*/ public void modifyBatchAttributes(final String bindDN, final String bindPassword) { // BEGIN modifyBatchAttributes() DirContext ldapContext = null; if (modificationItems.size() == 0) { throw new IllegalStateException("No modification items for batch"); } try { final Object[] tempModItems; final ModificationItem[] modItems; tempModItems = modificationItems.values().toArray(); modItems = new ModificationItem[tempModItems.length]; for (int index = 0; index < tempModItems.length; index++) { // convert to ModificationItem array modItems[index] = (ModificationItem) tempModItems[index]; } ldapContext = manager.getConnection(bindDN, bindPassword); ldapContext.modifyAttributes(getDn(), modItems); /** * Update the attributes in memory */ for (final ModificationItem modItem : modItems) { final Attribute attribute; attribute = modItem.getAttribute(); updateAttribute(attribute.getID()); } // manager.reloadAttributes(this); } catch (NamingException namingException) { throw new LdapNamingException(namingException); } catch (Exception exception) { throw new LdapNamingException("error modifying attributes", exception); } finally { try { if (ldapContext != null) { ldapContext.close(); } } catch (NamingException namingException) { manager.logNamingException(namingException); } // recreate empty batch list modificationItems = new LinkedHashMap(); } }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * Set next free uidNumber.//from w ww. ja v a 2s .co m */ 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); } }
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Synchronizes the roles between the application and the identity provider. * * @param username the user to synchronize the role for * @param role the role that should be set on the identity provider * @throws PortalServiceException for any errors encountered *///from w w w. j a v a 2s . co m private void synchRoles(String username, Role role) throws PortalServiceException { List<String> roles = findRoles(username); DirContext ctx = null; try { ctx = new InitialDirContext(env); // remove all roles, we expect only one for (String existingRole : roles) { if (!existingRole.equals(role.getDescription())) { removeRoleAssignment(ctx, username, existingRole); } } // add the new role if needed if (!roles.contains(role.getDescription())) { ModificationItem[] mods = new ModificationItem[1]; BasicAttribute m = new BasicAttribute(groupMemberAttr, MessageFormat.format(userDNPattern, username)); mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, m); ctx.modifyAttributes(MessageFormat.format(groupDNPattern, role.getDescription()), mods); } } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to reset password.", e); } finally { closeContext(ctx); } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); return false; }/*from www . j a va2 s. co m*/ NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute != null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException { String groupName = findGroupName(roleName); if (groupName == null) { log.warn("no group found for role '{}", roleName); groupName = roleName;/*from www .ja va2s. c o m*/ } NamingEnumeration<SearchResult> namingEnumeration = null; try { SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember()); if (attribute == null) { BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember()); basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) }); } else { attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn()); context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] { new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) }); } return true; } return false; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean registerUser(LDAPUser lus, UserRequest userReq, String OrgDN, String OrgUDN) { boolean registration = false; DirContext ctx = null; try {/*from w ww. j a v a 2 s . c o m*/ ctx = getAuthContext(lus.getUsername(), lus.getPassword()); Attributes attrsBag = new BasicAttributes(); Attribute oc = new BasicAttribute("objectClass"); oc.add("inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); oc.add("top"); attrsBag.put(oc); Attribute sn = new BasicAttribute("sn", userReq.getSurname()); attrsBag.put(sn); Attribute cn = new BasicAttribute("cn", userReq.getUsername()); attrsBag.put(cn); Attribute dispName = new BasicAttribute("displayName", userReq.getUsername()); attrsBag.put(dispName); Attribute uPass = new BasicAttribute("userPassword", userReq.getPassword()); attrsBag.put(uPass); Attribute regAdd = new BasicAttribute("registeredAddress", userReq.getPreferredMail()); attrsBag.put(regAdd); if (userReq.getTitle() != null && !userReq.getTitle().isEmpty()) { Attribute title = new BasicAttribute("title", userReq.getTitle()); attrsBag.put(title); } Attribute gName = new BasicAttribute("givenName", userReq.getGivenname()); attrsBag.put(gName); Attribute inits = new BasicAttribute("initials", userReq.getGivenname().substring(0, 1).toUpperCase() + userReq.getSurname().substring(0, 1).toUpperCase()); attrsBag.put(inits); Attribute mails = new BasicAttribute("mail"); mails.add(userReq.getPreferredMail()); for (String adMail : userReq.getAdditionalMails().split("[,\\s;]")) if (!adMail.isEmpty()) mails.add(adMail.trim()); attrsBag.put(mails); Attribute org = new BasicAttribute("o", OrgDN); attrsBag.put(org); if (OrgUDN != null && !OrgUDN.isEmpty()) { Attribute orgU = new BasicAttribute("ou", OrgUDN); attrsBag.put(orgU); } ResourceBundle rb = ResourceBundle.getBundle("ldap"); ctx.createSubcontext("cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"), attrsBag); ModificationItem[] modItems = new ModificationItem[1]; modItems[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("uniqueMember", "cn=" + userReq.getUsername() + "," + rb.getString("peopleRoot"))); ctx.modifyAttributes(rb.getString("usersGroup"), modItems); registration = true; } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(e); } finally { if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return registration; }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * change password of given user, needs old password for authentication. * * @param inUser/* w ww .j a va2 s .c om*/ * User object * @param inOldPassword * String * @param inNewPassword * String * @return boolean about result of change */ public boolean changeUserPassword(User inUser, String inOldPassword, String inNewPassword) throws NoSuchAlgorithmException { MD4 digester = new MD4(); Hashtable<String, String> env = getLdapConnectionSettings(); if (!ConfigCore.getBooleanParameter("ldap_readonly", false)) { env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin")); env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword")); try { DirContext ctx = new InitialDirContext(env); /* * Encryption of password and Base64-Encoding */ MessageDigest md = MessageDigest.getInstance(ConfigCore.getParameter("ldap_encryption", "SHA")); md.update(inNewPassword.getBytes(StandardCharsets.UTF_8)); String digestBase64 = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8); ModificationItem[] mods = new ModificationItem[4]; /* * UserPasswort-Attribut ndern */ BasicAttribute userpassword = new BasicAttribute("userPassword", "{" + ConfigCore.getParameter("ldap_encryption", "SHA") + "}" + digestBase64); /* * LanMgr-Passwort-Attribut ndern */ BasicAttribute lanmgrpassword = null; try { lanmgrpassword = new BasicAttribute("sambaLMPassword", LdapUser.toHexString(LdapUser.lmHash(inNewPassword))); // TODO: Don't catch super class exception, make sure that // the password isn't logged here } catch (Exception e) { logger.error(e); } /* * NTLM-Passwort-Attribut ndern */ BasicAttribute ntlmpassword = null; try { byte hmm[] = digester.digest(inNewPassword.getBytes("UnicodeLittleUnmarked")); ntlmpassword = new BasicAttribute("sambaNTPassword", LdapUser.toHexString(hmm)); } catch (UnsupportedEncodingException e) { // TODO: Make sure that the password isn't logged here logger.error(e); } BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet", String.valueOf(System.currentTimeMillis() / 1000l)); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userpassword); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrpassword); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmpassword); mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet); ctx.modifyAttributes(getUserDN(inUser), mods); // Close the context when we're done ctx.close(); return true; } catch (NamingException e) { logger.debug("Benutzeranmeldung nicht korrekt oder Passwortnderung nicht mglich", e); return false; } } return false; }