List of usage examples for javax.naming.directory ModificationItem ModificationItem
public ModificationItem(int mod_op, Attribute attr)
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;// w w w . jav a2s . c o m try { 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.sub.goobi.helper.ldap.Ldap.java
/** * Set next free uidNumber.//from w ww .ja v a2 s . c o 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:openscim.restful.server.resources.group.ldap.LdapGroupResource.java
@Override public Response updateGroup(UriInfo uriInfo, String gid, Group group) { // check the ldap template has been setup correctly if (ldapTemplate != null) { // create the mapper if it doesn't already exists if (mapper == null) mapper = new GroupAttributesMapper(properties); // build the group dn String dn = gid;//from w ww. j a v a 2 s . com if (properties .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS, GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS) .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) { // utilise ldap formated dn dn = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE, GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE) + "=" + gid + "," + properties.getProperty(GroupAttributesMapper.GROUP_BASEDN, GroupAttributesMapper.DEFAULT_GROUP_BASEDN); } try { // retrieve the group Group lookedupGroup = (Group) ldapTemplate.lookup(dn, mapper); // check if the group was found if (lookedupGroup == null) { // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + dn + " not found"); } List<ModificationItem> items = new ArrayList<ModificationItem>(); // build a gid modification //if(group.getId() != null) //{ // // get the gid attribute name // String gidAtttributeName = GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE; // if(properties.containsKey(GroupAttributesMapper.GID_ATTRIBUTE)) gidAtttributeName = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE); // // Attribute uidAttribute = new BasicAttribute(gidAtttributeName, group.getId()); // ModificationItem uidItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uidAttribute); // items.add(uidItem); //} // get the member attribute name String memberAtttributeName = properties.getProperty(GroupAttributesMapper.MEMBER_ATTRIBUTE, GroupAttributesMapper.DEFAULT_MEMBER_ATTRIBUTE); // set the members if (group.getAny() instanceof List) { List members = (List) group.getAny(); Attribute memberAttribute = new BasicAttribute(memberAtttributeName); for (Object object : members) { if (object instanceof PluralAttribute) { PluralAttribute member = (PluralAttribute) object; String uid = member.getValue(); // build the user dn String userdn = uid; if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { // utilise ldap formated dn userdn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + uid + "," + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN, UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN); } memberAttribute.add(userdn); } } ModificationItem memberItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, memberAttribute); items.add(memberItem); } // update the user password ModificationItem[] itemsArray = items.toArray(new ModificationItem[items.size()]); ldapTemplate.modifyAttributes(dn, itemsArray); // password changed successfully return Response.status(HttpStatus.NO_CONTENT.getCode()).build(); } catch (Exception nException) { logger.debug("Resource " + dn + " not found"); logger.debug(nException); // group not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + dn + " not found"); } } else { // ldap not configured logger.error("ldap not configured"); // return a server error return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider group ldap repository not configured"); } }
From source file:openscim.restful.server.resources.user.ldap.LdapUserResource.java
@Override public Response updateUser(UriInfo uriInfo, String uid, User user) { // check the ldap template has been setup correctly if (ldapTemplate != null) { // create the mapper if it doesn't already exists if (mapper == null) mapper = new UserAttributesMapper(properties); // build the user dn String dn = user.getId(); if (properties .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS) .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) { // utilise ldap formated dn dn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + user.getId() + "," + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN, UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN); }/*w w w . j ava 2s .co m*/ try { // retrieve the user User lookedupUser = (User) ldapTemplate.lookup(dn, mapper); // check if the user was found if (lookedupUser == null) { logger.debug("Resource " + dn + " not found"); // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + uid + " not found"); } List<ModificationItem> items = new ArrayList<ModificationItem>(); // get the uid attribute name //String uidAtttributeName = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE, UserAttributesMapper.DEFAULT_UID_ATTRIBUTE); // build a uid modification //if(user.getId() != null) //{ // Attribute uidAttribute = new BasicAttribute(uidAtttributeName, user.getId()); // ModificationItem uidItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, uidAttribute); // items.add(uidItem); //} // get the display name attribute name String displayAtttributeName = properties.getProperty(UserAttributesMapper.DISPLAYNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_DISPLAYNAME_ATTRIBUTE); // build a cn modification if (user.getDisplayName() != null) { Attribute cnAttribute = new BasicAttribute(displayAtttributeName, user.getDisplayName()); ModificationItem cnItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, cnAttribute); items.add(cnItem); } // build names modification if (user.getName() != null) { // get the surname attribute name String surnameAtttributeName = properties.getProperty(UserAttributesMapper.FAMILYNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_FAMILYNAME_ATTRIBUTE); // get the given name attribute name String givenAtttributeName = properties.getProperty(UserAttributesMapper.GIVENNAME_ATTRIBUTE, UserAttributesMapper.DEFAULT_GIVENNAME_ATTRIBUTE); if (user.getName().getFamilyName() != null) { Attribute snAttribute = new BasicAttribute(surnameAtttributeName, user.getName().getFamilyName()); ModificationItem snItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, snAttribute); items.add(snItem); } if (user.getName().getGivenName() != null) { Attribute gnAttribute = new BasicAttribute(givenAtttributeName, user.getName().getGivenName()); ModificationItem gnItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, gnAttribute); items.add(gnItem); } } // set the emails if (user.getEmails() != null) { // get the email attribute name String mailAtttributeName = properties.getProperty(UserAttributesMapper.MAIL_ATTRIBUTE, UserAttributesMapper.DEFAULT_MAIL_ATTRIBUTE); Attribute emailAttribute = new BasicAttribute(mailAtttributeName); List<PluralAttribute> emails = user.getEmails().getEmail(); for (PluralAttribute email : emails) { emailAttribute.add(email.getValue()); } ModificationItem emailItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, emailAttribute); items.add(emailItem); } // set the telephones if (user.getPhoneNumbers() != null) { // get the telephone attribute name String telephoneAtttributeName = properties.getProperty( UserAttributesMapper.TELEPHONE_ATTRIBUTE, UserAttributesMapper.DEFAULT_TELEPHONE_ATTRIBUTE); Attribute telephoneAttribute = new BasicAttribute(telephoneAtttributeName); List<PluralAttribute> telephones = user.getPhoneNumbers().getPhoneNumber(); for (PluralAttribute telephone : telephones) { telephoneAttribute.add(telephone.getValue()); } ModificationItem telephoneItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, telephoneAttribute); items.add(telephoneItem); } // build a password modification if (user.getPassword() != null) { // get the password attribute name String passwordAtttributeName = properties.getProperty(UserAttributesMapper.PASSWORD_ATTRIBUTE, UserAttributesMapper.DEFAULT_PASSWORD_ATTRIBUTE); Attribute passwordAttribute = new BasicAttribute(passwordAtttributeName, user.getPassword()); ModificationItem passwordItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, passwordAttribute); items.add(passwordItem); } // update the user password ModificationItem[] itemsArray = items.toArray(new ModificationItem[items.size()]); ldapTemplate.modifyAttributes(dn, itemsArray); // password changed successfully return Response.status(HttpStatus.NO_CONTENT.getCode()).build(); } catch (Exception nException) { logger.debug("Resource " + dn + " not found"); logger.debug(nException); // user not found, return an error message return ResourceUtilities.buildErrorResponse(HttpStatus.NOT_FOUND, "Resource " + uid + " not found"); } } else { // ldap not configured logger.error("ldap not configured"); // return a server error return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider user ldap repository not configured"); } }
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;/*ww w. j ava 2 s. c om*/ } 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:de.sub.goobi.helper.ldap.Ldap.java
/** * change password of given user, needs old password for authentication. * * @param inUser//ww w . j a v a 2s.c o m * 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; }
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 w ww .j a va 2 s. 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 + "," + 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: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;//from w w w. j a va 2s. c o m try { 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:it.infn.ct.security.utilities.LDAPUtils.java
public static boolean resetPassword(String cn, String newPassword) { DirContext ctx = null;//ww w . j ava 2 s . co m try { ctx = getMainAuthContext(); ModificationItem[] modItems = new ModificationItem[1]; modItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", newPassword)); ResourceBundle rb = ResourceBundle.getBundle("ldap"); ctx.modifyAttributes("cn=" + cn + "," + rb.getString("peopleRoot"), modItems); } catch (NamingException ex) { _log.error(ex); return false; } return true; }