List of usage examples for javax.naming.directory BasicAttribute BasicAttribute
public BasicAttribute(String id, boolean ordered)
From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java
private void changePasswordUsingAttributeModification(DistinguishedName userDn, String oldPassword, String newPassword) {//from w w w. j av a2 s. c o m final ModificationItem[] passwordChange = new ModificationItem[] { new ModificationItem( DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(passwordAttributeName, newPassword)) }; if (oldPassword == null) { template.modifyAttributes(userDn, passwordChange); return; } template.executeReadWrite(dirCtx -> { LdapContext ctx = (LdapContext) dirCtx; ctx.removeFromEnvironment("com.sun.jndi.ldap.connect.pool"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, LdapUtils.getFullDn(userDn, ctx).toString()); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, oldPassword); // TODO: reconnect doesn't appear to actually change the credentials try { ctx.reconnect(null); } catch (javax.naming.AuthenticationException e) { throw new BadCredentialsException("Authentication for password change failed."); } ctx.modifyAttributes(userDn, passwordChange); return null; }); }
From source file:org.gcaldaemon.core.ldap.LDAPListener.java
private final ByteBuffer processRequest(LdapMessage request, boolean utf8) throws Exception { if (log.isDebugEnabled()) { try {/*from ww w .j a v a2 s. c o m*/ String command = request.getMessageTypeName(); if (command != null) { command = command.toLowerCase().replace('_', ' '); } log.debug("Processing " + command + "..."); } catch (Exception ignored) { log.warn("Processing unknown LDAP request..."); } } LinkedList list = new LinkedList(); switch (request.getMessageType()) { case LdapConstants.BIND_REQUEST: // Bind response BindResponse bind = new BindResponse(); bind.setMessageId(request.getMessageId()); LdapResult result = new LdapResult(); result.setResultCode(0); bind.setLdapResult(result); list.addLast(bind); break; case LdapConstants.UNBIND_REQUEST: // Unbind response LdapResponse unbind = new LdapResponse(); unbind.setMessageId(request.getMessageId()); result = new LdapResult(); result.setResultCode(0); unbind.setLdapResult(result); list.addLast(unbind); break; case LdapConstants.SEARCH_REQUEST: // Switch back encoding if (nativeCharsetLocked) { utf8 = false; } // Get search string SearchRequest search = request.getSearchRequest(); Filter filter = search.getTerminalFilter(); String key = null; if (filter == null) { filter = search.getFilter(); if (filter == null) { filter = search.getCurrentFilter(); } } if (filter != null) { if (filter instanceof SubstringFilter) { SubstringFilter substringFilter = (SubstringFilter) filter; ArrayList substrings = substringFilter.getAnySubstrings(); if (substrings != null && substrings.size() != 0) { key = (String) substrings.get(0); } } if (key == null) { key = filter.toString(); if (key != null) { if (key.charAt(0) == '*') { key = key.substring(1); } if (key.charAt(key.length() - 1) == '*') { key = key.substring(0, key.length() - 1); } if (key.indexOf('=') != -1) { key = key.substring(key.indexOf('=') + 1); } } } if (key != null) { if (key.length() == 0) { key = null; } else { // Decode UTF8 chars try { byte[] bytes = key.getBytes(PLATFORM_ENCODING); key = StringUtils.decodeToString(bytes, StringUtils.UTF_8); if (utf8) { bytes = key.getBytes(PLATFORM_ENCODING); key = StringUtils.decodeToString(bytes, StringUtils.UTF_8); } } catch (Exception ignored) { } if (log.isDebugEnabled()) { log.debug("LDAP search filter (" + key + ") readed."); } key = key.toLowerCase(); // All contacts requested if (key.equals("@")) { key = null; } } } } // Handle native charset lock if (key != null && !utf8) { nativeCharsetLocked = true; } // Find entry GmailContact[] contacts = loader.getContacts(); if (contacts != null) { GmailContact contact; for (int n = 0; n < contacts.length; n++) { contact = contacts[n]; if (key != null && contact.name.toLowerCase().indexOf(key) == -1) { continue; } // Add search entry SearchResultEntry entry = new SearchResultEntry(); entry.setMessageId(request.getMessageId()); LdapDN name; try { name = new LdapDN("CN=" + encode(contact.name, utf8)); } catch (Exception badDN) { log.debug(badDN); continue; } entry.setObjectName(name); BasicAttributes partialAttributeList = new BasicAttributes(true); partialAttributeList.put(new BasicAttribute("cn", encode(contact.name, utf8))); if (contact.email.length() != 0) { // first email partialAttributeList.put(new BasicAttribute("mail", encode(contact.email, utf8))); } if (contact.notes.length() != 0) { // notes partialAttributeList.put(new BasicAttribute("comment", encode(contact.notes, utf8))); partialAttributeList.put(new BasicAttribute("description", encode(contact.notes, utf8))); } String mobile = contact.mobile; if (mobile.length() == 0) { mobile = contact.phone; } if (mobile.length() != 0) { // mobile phone partialAttributeList.put(new BasicAttribute("telephonenumber", encode(mobile, utf8))); } if (contact.phone.length() != 0) { // homePhone partialAttributeList.put(new BasicAttribute("homePhone", encode(contact.phone, utf8))); } if (contact.mail.length() != 0) { // second email partialAttributeList .put(new BasicAttribute("mozillaSecondEmail", encode(contact.mail, utf8))); partialAttributeList .put(new BasicAttribute("mailAlternateAddress", encode(contact.mail, utf8))); } if (contact.address.length() != 0) { // postal address partialAttributeList .put(new BasicAttribute("postalAddress", encode(contact.address, utf8))); partialAttributeList .put(new BasicAttribute("homePostalAddress", encode(contact.address, utf8))); partialAttributeList.put(new BasicAttribute("homeStreet", encode(contact.address, utf8))); } if (contact.pager.length() != 0) { // pager partialAttributeList.put(new BasicAttribute("pager", encode(contact.pager, utf8))); } if (contact.fax.length() != 0) { // fax partialAttributeList .put(new BasicAttribute("facsimileTelephoneNumber", encode(contact.fax, utf8))); if (contact.pager.length() == 0) { partialAttributeList.put(new BasicAttribute("pager", encode(contact.fax, utf8))); } } if (contact.title.length() != 0) { // title partialAttributeList.put(new BasicAttribute("title", encode(contact.title, utf8))); } if (contact.company.length() != 0) { // company partialAttributeList.put(new BasicAttribute("company", encode(contact.company, utf8))); partialAttributeList.put(new BasicAttribute("o", encode(contact.company, utf8))); } entry.setPartialAttributeList(partialAttributeList); list.addLast(entry); } } // Search done if (log.isDebugEnabled()) { log.debug("Found " + list.size() + " contacts."); } SearchResultDone done = new SearchResultDone(); done.setMessageId(request.getMessageId()); result = new LdapResult(); result.setResultCode(0); done.setLdapResult(result); list.addLast(done); break; case LdapConstants.ABANDON_REQUEST: // Abandon command result = new LdapResult(); result.setResultCode(0); LdapResponse response = new LdapResponse(); response.setLdapResult(result); list.addLast(response); break; default: // Unsupported command log.debug("Unsupported LDAP command!"); result = new LdapResult(); result.setErrorMessage("Unsupported LDAP command!"); response = new LdapResponse(); response.setLdapResult(result); list.addLast(response); } log.debug("LDAP request processed."); if (!list.isEmpty()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Iterator responses = list.iterator(); while (responses.hasNext()) { LdapMessage response = (LdapMessage) responses.next(); response.setMessageId(request.getMessageId()); // Append LDAP response LdapMessage message = new LdapMessage(); message.setProtocolOP(response); message.setMessageId(request.getMessageId()); ByteBuffer bb = message.encode(null); byte[] a = bb.array(); out.write(a); } byte[] bytes = out.toByteArray(); return ByteBuffer.wrap(bytes); } return null; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java
/** * Checks attribute if it has to be written to LDAP or removed from LDAP if attribute = null, its like not set. * /*from w w w . ja va 2s . com*/ * @param pOrgAtt: ConstEnumOrgStatus or ConstEnumOrgSector * @param pOldOrgAtt * @param ldapAttributeName * @param vOrgAttributes * @param vOrgRemoveAttributes * @param isUpdate */ private boolean checkAttribute(Enum<?> pOrgAtt, Enum<?> pOldOrgAtt, String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) { boolean hasChanged = false; if (!isUpdate) { if (pOldOrgAtt != null && pOrgAtt != null) { vOrgAttributes.put(new BasicAttribute(ldapAttributeName, String.valueOf(pOrgAtt.name()))); } } else { if ((pOrgAtt != null) && ((pOldOrgAtt == null) || (pOldOrgAtt != pOrgAtt))) { vOrgAttributes.put(ldapAttributeName, String.valueOf(pOrgAtt)); hasChanged = true; } else if ((pOrgAtt == null) && (pOldOrgAtt != null)) { vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName)); hasChanged = true; } } return hasChanged; }
From source file:org.gldapdaemon.core.ldap.LDAPListener.java
private final ByteBuffer processRequest(LdapMessage request, boolean utf8) throws Exception { if (log.isDebugEnabled()) { try {/*from w ww.j a v a 2 s. co m*/ String command = request.getMessageTypeName(); if (command != null) { command = command.toLowerCase().replace('_', ' '); } log.debug("Processing " + command + "..."); } catch (Exception ignored) { log.warn("Processing unknown LDAP request..."); } } LinkedList list = new LinkedList(); switch (request.getMessageType()) { case LdapConstants.BIND_REQUEST: // Bind response BindResponse bind = new BindResponse(); bind.setMessageId(request.getMessageId()); LdapResult result = new LdapResult(); result.setResultCode(0); bind.setLdapResult(result); list.addLast(bind); break; case LdapConstants.UNBIND_REQUEST: // Unbind response LdapResponse unbind = new LdapResponse(); unbind.setMessageId(request.getMessageId()); result = new LdapResult(); result.setResultCode(0); unbind.setLdapResult(result); list.addLast(unbind); break; case LdapConstants.SEARCH_REQUEST: // Switch back encoding if (nativeCharsetLocked) { utf8 = false; } // Get search string SearchRequest search = request.getSearchRequest(); Filter filter = search.getTerminalFilter(); String key = null; if (filter == null) { filter = search.getFilter(); if (filter == null) { filter = search.getCurrentFilter(); } } if (filter != null) { if (filter instanceof SubstringFilter) { SubstringFilter substringFilter = (SubstringFilter) filter; ArrayList substrings = substringFilter.getAnySubstrings(); if (substrings != null && substrings.size() != 0) { key = (String) substrings.get(0); } } if (key == null) { key = filter.toString(); if (key != null) { if (key.charAt(0) == '*') { key = key.substring(1); } if (key.charAt(key.length() - 1) == '*') { key = key.substring(0, key.length() - 1); } if (key.indexOf('=') != -1) { key = key.substring(key.indexOf('=') + 1); } } } if (key != null) { if (key.length() == 0) { key = null; } else { // Decode UTF8 chars try { byte[] bytes = key.getBytes(PLATFORM_ENCODING); key = StringUtils.decodeToString(bytes, StringUtils.UTF_8); if (utf8) { bytes = key.getBytes(PLATFORM_ENCODING); key = StringUtils.decodeToString(bytes, StringUtils.UTF_8); } } catch (Exception ignored) { } if (log.isDebugEnabled()) { log.debug("LDAP search filter (" + key + ") received."); } key = key.toLowerCase(); // All contacts requested if (key.equals("@")) { key = null; } } } } // Handle native charset lock if (key != null && !utf8) { nativeCharsetLocked = true; } // Find entry ArrayList<GmailContact> contacts = loader.getContacts(); if (contacts != null) { GmailContact contact; for (int n = 0; n < contacts.size(); n++) { contact = contacts.get(n); String value = null; if (contact.name.toLowerCase().indexOf(key) >= 0 || contact.company.toLowerCase().indexOf(key) >= 0) { value = contact.name.length() > 0 ? contact.name : contact.company; } else if (key != null) { continue; } // Add search entry SearchResultEntry entry = new SearchResultEntry(); entry.setMessageId(request.getMessageId()); LdapDN name; try { name = new LdapDN("CN=" + encode(value, utf8)); } catch (Exception badDN) { log.debug(badDN); continue; } entry.setObjectName(name); BasicAttributes partialAttributeList = new BasicAttributes(true); partialAttributeList.put(new BasicAttribute("cn", encode(value, utf8))); if (contact.email.length() != 0) { // first email partialAttributeList.put(new BasicAttribute("mail", encode(contact.email, utf8))); } if (contact.notes.length() != 0) { // notes partialAttributeList.put(new BasicAttribute("comment", encode(contact.notes, utf8))); partialAttributeList.put(new BasicAttribute("description", encode(contact.notes, utf8))); } String mobile = contact.mobile; if (mobile.length() == 0) { mobile = contact.phone; } if (mobile.length() != 0) { // mobile phone partialAttributeList.put(new BasicAttribute("telephonenumber", encode(mobile, utf8))); } if (contact.phone.length() != 0) { // homePhone partialAttributeList.put(new BasicAttribute("homePhone", encode(contact.phone, utf8))); } if (contact.mail.length() != 0) { // second email partialAttributeList .put(new BasicAttribute("mozillaSecondEmail", encode(contact.mail, utf8))); partialAttributeList .put(new BasicAttribute("mailAlternateAddress", encode(contact.mail, utf8))); } if (contact.address.length() != 0) { // postal address partialAttributeList .put(new BasicAttribute("postalAddress", encode(contact.address, utf8))); partialAttributeList .put(new BasicAttribute("homePostalAddress", encode(contact.address, utf8))); partialAttributeList.put(new BasicAttribute("homeStreet", encode(contact.address, utf8))); } if (contact.pager.length() != 0) { // pager partialAttributeList.put(new BasicAttribute("pager", encode(contact.pager, utf8))); } if (contact.fax.length() != 0) { // fax partialAttributeList .put(new BasicAttribute("facsimileTelephoneNumber", encode(contact.fax, utf8))); if (contact.pager.length() == 0) { partialAttributeList.put(new BasicAttribute("pager", encode(contact.fax, utf8))); } } if (contact.title.length() != 0) { // title partialAttributeList.put(new BasicAttribute("title", encode(contact.title, utf8))); } if (contact.company.length() != 0) { // company partialAttributeList.put(new BasicAttribute("company", encode(contact.company, utf8))); partialAttributeList.put(new BasicAttribute("o", encode(contact.company, utf8))); } entry.setPartialAttributeList(partialAttributeList); list.addLast(entry); } } // Search done if (log.isDebugEnabled()) { log.debug("Found " + list.size() + " contacts."); } SearchResultDone done = new SearchResultDone(); done.setMessageId(request.getMessageId()); result = new LdapResult(); result.setResultCode(0); done.setLdapResult(result); list.addLast(done); break; case LdapConstants.ABANDON_REQUEST: // Abandon command result = new LdapResult(); result.setResultCode(0); LdapResponse response = new LdapResponse(); response.setLdapResult(result); list.addLast(response); break; default: // Unsupported command log.debug("Unsupported LDAP command!"); result = new LdapResult(); result.setErrorMessage("Unsupported LDAP command!"); response = new LdapResponse(); response.setLdapResult(result); list.addLast(response); } log.debug("LDAP request processed."); if (!list.isEmpty()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Iterator responses = list.iterator(); while (responses.hasNext()) { LdapMessage response = (LdapMessage) responses.next(); response.setMessageId(request.getMessageId()); // Append LDAP response LdapMessage message = new LdapMessage(); message.setProtocolOP(response); message.setMessageId(request.getMessageId()); ByteBuffer bb = message.encode(null); byte[] a = bb.array(); out.write(a); } byte[] bytes = out.toByteArray(); return ByteBuffer.wrap(bytes); } return null; }
From source file:org.projectforge.business.ldap.LdapUserDao.java
public void changePassword(final LdapUser user, final String oldPassword, final String newPassword) { log.info("Change password for " + getObjectClass() + ": " + buildDn(null, user)); final List<ModificationItem> modificationItems = new ArrayList<ModificationItem>(); if (oldPassword != null) { modificationItems.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("userPassword", oldPassword))); modificationItems.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("userPassword", newPassword))); } else {//from w ww . ja v a 2s. c o m modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userPassword", newPassword))); } if (isSambaAccountsConfigured() == true && user.getSambaSIDNumber() != null) { final String sambaNTPassword = SmbEncrypt.NTUNICODEHash(newPassword); modificationItems.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("sambaNTPassword", sambaNTPassword))); } // Perform the update modify(user, modificationItems); }
From source file:CreateJavaSchema.java
/** * Inserts attribute definitions from RFC 2713 into the schema. * * This method maps the LDAP schema definitions in RFC 2713 onto the * proprietary attributes required by the Active Directory schema. * * The resulting attribute definitions are identical to those of RFC 2713. *//*w w w .ja v a2 s. c om*/ protected void insertADAttributes(DirContext rootCtx, DirContext schemaCtx) throws NamingException { System.out.println(" [inserting new attribute definitions ...]"); String dn = schemaCtx.getNameInNamespace(); String attrID; attrID = new String("javaClassName"); Attributes attrs1 = new BasicAttributes(); attrs1.put(new BasicAttribute("adminDescription", attrID)); attrs1.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.6")); attrs1.put(new BasicAttribute("attributeSyntax", "2.5.5.12")); attrs1.put(new BasicAttribute("cn", attrID)); attrs1.put( new BasicAttribute("description", "Fully qualified name of distinguished Java class or interface")); attrs1.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs1.put(new BasicAttribute("isSingleValued", "TRUE")); attrs1.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs1.put(new BasicAttribute("name", attrID)); attrs1.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs1.put(new BasicAttribute("objectClass", "attributeSchema")); attrs1.put(new BasicAttribute("oMSyntax", "64")); attrs1.put(new BasicAttribute("searchFlags", "0")); attrs1.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs1); System.out.println(" [" + attrID + "]"); attrID = new String("javaCodeBase"); Attributes attrs2 = new BasicAttributes(); attrs2.put(new BasicAttribute("adminDescription", attrID)); attrs2.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.7")); attrs2.put(new BasicAttribute("attributeSyntax", "2.5.5.5")); attrs2.put(new BasicAttribute("cn", attrID)); attrs2.put(new BasicAttribute("description", "URL(s) specifying the location of class definition")); attrs2.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs2.put(new BasicAttribute("isSingleValued", "FALSE")); attrs2.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs2.put(new BasicAttribute("name", attrID)); attrs2.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs2.put(new BasicAttribute("objectClass", "attributeSchema")); attrs2.put(new BasicAttribute("oMSyntax", "22")); attrs2.put(new BasicAttribute("searchFlags", "0")); attrs2.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs2); System.out.println(" [" + attrID + "]"); attrID = new String("javaSerializedData"); Attributes attrs3 = new BasicAttributes(); attrs3.put(new BasicAttribute("adminDescription", attrID)); attrs3.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.8")); attrs3.put(new BasicAttribute("attributeSyntax", "2.5.5.10")); attrs3.put(new BasicAttribute("cn", attrID)); attrs3.put(new BasicAttribute("description", "Serialized form of a Java object")); attrs3.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs3.put(new BasicAttribute("isSingleValued", "TRUE")); attrs3.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs3.put(new BasicAttribute("name", attrID)); attrs3.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs3.put(new BasicAttribute("objectClass", "attributeSchema")); attrs3.put(new BasicAttribute("oMSyntax", "4")); attrs3.put(new BasicAttribute("searchFlags", "0")); attrs3.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs3); System.out.println(" [" + attrID + "]"); attrID = new String("javaFactory"); Attributes attrs4 = new BasicAttributes(); attrs4.put(new BasicAttribute("adminDescription", attrID)); attrs4.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.10")); attrs4.put(new BasicAttribute("attributeSyntax", "2.5.5.12")); attrs4.put(new BasicAttribute("cn", attrID)); attrs4.put(new BasicAttribute("description", "Fully qualified Java class name of a JNDI object factory")); attrs4.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs4.put(new BasicAttribute("isSingleValued", "TRUE")); attrs4.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs4.put(new BasicAttribute("name", attrID)); attrs4.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs4.put(new BasicAttribute("objectClass", "attributeSchema")); attrs4.put(new BasicAttribute("oMSyntax", "64")); attrs4.put(new BasicAttribute("searchFlags", "0")); attrs4.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs4); System.out.println(" [" + attrID + "]"); attrID = new String("javaReferenceAddress"); Attributes attrs5 = new BasicAttributes(); attrs5.put(new BasicAttribute("adminDescription", attrID)); attrs5.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.11")); attrs5.put(new BasicAttribute("attributeSyntax", "2.5.5.12")); attrs5.put(new BasicAttribute("cn", attrID)); attrs5.put(new BasicAttribute("description", "Addresses associated with a JNDI Reference")); attrs5.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs5.put(new BasicAttribute("isSingleValued", "FALSE")); attrs5.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs5.put(new BasicAttribute("name", attrID)); attrs5.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs5.put(new BasicAttribute("objectClass", "attributeSchema")); attrs5.put(new BasicAttribute("oMSyntax", "64")); attrs5.put(new BasicAttribute("searchFlags", "0")); attrs5.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs5); System.out.println(" [" + attrID + "]"); attrID = new String("javaDoc"); Attributes attrs6 = new BasicAttributes(); attrs6.put(new BasicAttribute("adminDescription", attrID)); attrs6.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.12")); attrs6.put(new BasicAttribute("attributeSyntax", "2.5.5.5")); attrs6.put(new BasicAttribute("cn", attrID)); attrs6.put(new BasicAttribute("description", "The Java documentation for the class")); attrs6.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs6.put(new BasicAttribute("isSingleValued", "FALSE")); attrs6.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs6.put(new BasicAttribute("name", attrID)); attrs6.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs6.put(new BasicAttribute("objectClass", "attributeSchema")); attrs6.put(new BasicAttribute("oMSyntax", "22")); attrs6.put(new BasicAttribute("searchFlags", "0")); attrs6.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs6); System.out.println(" [" + attrID + "]"); attrID = new String("javaClassNames"); Attributes attrs7 = new BasicAttributes(); attrs7.put(new BasicAttribute("adminDescription", attrID)); attrs7.put(new BasicAttribute("attributeID", "1.3.6.1.4.1.42.2.27.4.1.13")); attrs7.put(new BasicAttribute("attributeSyntax", "2.5.5.12")); attrs7.put(new BasicAttribute("cn", attrID)); attrs7.put(new BasicAttribute("description", "Fully qualified Java class or interface name")); attrs7.put(new BasicAttribute("distinguishedName", "CN=" + attrID + "," + dn)); attrs7.put(new BasicAttribute("isSingleValued", "FALSE")); attrs7.put(new BasicAttribute("lDAPDisplayName", attrID)); attrs7.put(new BasicAttribute("name", attrID)); attrs7.put(new BasicAttribute("objectCategory", "CN=Attribute-Schema," + dn)); attrs7.put(new BasicAttribute("objectClass", "attributeSchema")); attrs7.put(new BasicAttribute("oMSyntax", "64")); attrs7.put(new BasicAttribute("searchFlags", "0")); attrs7.put(new BasicAttribute("systemOnly", "FALSE")); schemaCtx.createSubcontext("cn=" + attrID, attrs7); System.out.println(" [" + attrID + "]"); flushADSchemaMods(rootCtx); // finally }
From source file:de.sub.goobi.helper.ldap.Ldap.java
/** * change password of given user, needs old password for authentication. * * @param inUser/*from ww w. j a v a 2 s.com*/ * 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: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 av a 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:edu.lafayette.metadb.model.userman.UserManDAO.java
/** * Get the LDAP DN for a user.//from w ww . j a va 2s. c o m * @param searchUser * @param searchPassword * @param userName * @return */ @SuppressWarnings("unchecked") private static String getDN(String searchUser, String searchPassword, String userName) { // The resultant DN String result; // Set up environment for creating initial context Hashtable env = new Hashtable(11); env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL); // Use admin credencials for search// Authenticate env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple"); env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser); env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword); DirContext ctx = null; try { // Create initial context ctx = new InitialDirContext(env); //MetaDbHelper.note("Created LDAP context"); Attributes matchAttrs = new BasicAttributes(true); matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName)); //MetaDbHelper.note("Created attributes"); // look up attributes try { //MetaDbHelper.note("Setting up query"); SearchControls ctrls = new SearchControls(); ctrls.setSearchScope(Global.LDAP_SCOPE); NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT, "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls); //MetaDbHelper.note("NamingEnumeration retrieved"); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) { result = sr.getName(); } else { result = (sr.getName() + "," + Global.LDAP_CONTEXT); } //MetaDbHelper.note("Got DN: "+result); return result; } } catch (NamingException e) { MetaDbHelper.logEvent(e); //MetaDbHelper.note("LDAP Error: Failed Search"); } } catch (NamingException e) { MetaDbHelper.logEvent(e); //MetaDbHelper.note("LDAP Error: Failed authentication"); } finally { // Close the context when we're done try { if (ctx != null) ctx.close(); } catch (NamingException e) { } } // No DN match found return null; }