Example usage for javax.naming.directory DirContext modifyAttributes

List of usage examples for javax.naming.directory DirContext modifyAttributes

Introduction

In this page you can find the example usage for javax.naming.directory DirContext modifyAttributes.

Prototype

public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException;

Source Link

Document

Modifies the attributes associated with a named object using an ordered list of modifications.

Usage

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationChangeUnicodePwd(String entryName, ParameterResolutionContext prc,
        Map paramValueMap) throws SenderException, ParameterException {
    ModificationItem[] modificationItems = new ModificationItem[2];
    modificationItems[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("oldPassword"))));
    modificationItems[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("newPassword"))));
    DirContext dirContext = null;
    try {/*from w w  w  . j  av a 2 s . c o  m*/
        dirContext = getDirContext(paramValueMap);
        dirContext.modifyAttributes(entryName, modificationItems);
        return DEFAULT_RESULT_CHANGE_UNICODE_PWD_OK;
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   19 LDAP_CONSTRAINT_VIOLATION Indicates that the attribute value specified in a modify, add, or modify DN operation violates constraints placed on the attribute. The constraint can be one of size or content (string only, no binary).
        // AD:
        //   [LDAP: error code 19 - 0000052D: AtrErr: DSID-03191041, #1...
        if (e.getMessage().startsWith("[LDAP: error code 19 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation()
                        + "] old password doesn't match or new password doesn't comply with policy for: "
                        + entryName);
            return DEFAULT_RESULT_CHANGE_UNICODE_PWD_NOK;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

From source file:org.easy.ldap.LdapDao.java

public void updateRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {//w  w  w  .j a v  a  2 s  .c  om
        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);
            }
        }
    }
}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*from   w  w  w.j a  v a 2  s . c o  m*/
 * @param type
 * @param rdnValue
 */
public void addRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }

}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn//from  w  w w.j a  v  a 2s  . co  m
 * @param type
 * @param rdnValue
 */
public void removeRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.REMOVE_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);
            }
        }
    }

}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*from  w w w. j av a  2  s . c  om*/
 * @param subContextName
 * @param modifications
 */
public void updateSubContext(LdapName rootDn, LdapName subContextName, ModificationItem[] modifications) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());
        ctx.modifyAttributes(subContextName, modifications);
    } catch (NamingException e) {
        throw new RuntimeException(subContextName.toString() + "," + rootDn, e);
    } finally {
        if (contextFactory != null)
            contextFactory.closeContext(ctx);
    }

}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

private void modifyAuthorities(final DistinguishedName userDn,
        final Collection<? extends GrantedAuthority> authorities, final int modType) {
    template.executeReadWrite(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws NamingException {
            for (GrantedAuthority authority : authorities) {
                String group = convertAuthorityToGroup(authority);
                DistinguishedName fullDn = LdapUtils.getFullDn(userDn, ctx);
                ModificationItem addGroup = new ModificationItem(modType,
                        new BasicAttribute(groupMemberAttributeName, fullDn.toUrl()));

                ctx.modifyAttributes(buildGroupDn(group), new ModificationItem[] { addGroup });
            }//w  w w . j a  va2  s .co  m
            return null;
        }
    });
}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Set next free uidNumber.//  w w  w .j  ava2s  . co m
 */
private void setNextUidNumber(LdapServer ldapServer) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(ldapServer);
    DirContext ctx;

    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes attrs = ctx.getAttributes(ldapServer.getNextFreeUnixIdPattern());
        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(ldapServer.getNextFreeUnixIdPattern(), mods);

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

}

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param user//from  w w  w . j  a  v a  2 s.  c om
 *            User object
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User user, String inNewPassword) throws NoSuchAlgorithmException {
    JDKMessageDigest.MD4 digester = new JDKMessageDigest.MD4();
    PasswordEncryption passwordEncryption = user.getLdapGroup().getLdapServer().getPasswordEncryption();
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (!user.getLdapGroup().getLdapServer().isReadOnly()) {
        try {
            ModificationItem[] mods = new ModificationItem[4];

            // encryption of password and Base64-Encoding
            MessageDigest md = MessageDigest.getInstance(passwordEncryption.getTitle());
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String encryptedPassword = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);

            // change attribute userPassword
            BasicAttribute userPassword = new BasicAttribute("userPassword",
                    "{" + passwordEncryption + "}" + encryptedPassword);
            mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPassword);

            // change attribute lanmgrPassword
            BasicAttribute lanmgrPassword = proceedPassword("sambaLMPassword", inNewPassword, null);
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, lanmgrPassword);

            // change attribute ntlmPassword
            BasicAttribute ntlmPassword = proceedPassword("sambaNTPassword", inNewPassword, digester);
            mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ntlmPassword);

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000L));
            mods[3] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, sambaPwdLastSet);

            DirContext ctx = new InitialDirContext(env);
            ctx.modifyAttributes(buildUserDN(user), 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.kitodo.services.data.LdapServerService.java

/**
 * change password of given user, needs old password for authentication.
 *
 * @param user// w  w  w  .ja  v  a 2s  .c o  m
 *            User object
 * @param inNewPassword
 *            String
 * @return boolean about result of change
 */
public boolean changeUserPassword(User user, String inNewPassword) throws NoSuchAlgorithmException {
    JDKMessageDigest.MD4 digester = new JDKMessageDigest.MD4();
    PasswordEncryption passwordEncryption = user.getLdapGroup().getLdapServer().getPasswordEncryptionEnum();
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (!user.getLdapGroup().getLdapServer().isReadOnly()) {
        try {
            // encryption of password and Base64-Encoding
            MessageDigest md = MessageDigest.getInstance(passwordEncryption.getTitle());
            md.update(inNewPassword.getBytes(StandardCharsets.UTF_8));
            String encryptedPassword = new String(Base64.encodeBase64(md.digest()), StandardCharsets.UTF_8);

            // change attribute userPassword
            BasicAttribute userPassword = new BasicAttribute("userPassword",
                    "{" + passwordEncryption + "}" + encryptedPassword);

            // change attribute lanmgrPassword
            BasicAttribute lanmgrPassword = proceedPassword("sambaLMPassword", inNewPassword, null);

            // change attribute ntlmPassword
            BasicAttribute ntlmPassword = proceedPassword("sambaNTPassword", inNewPassword, digester);

            BasicAttribute sambaPwdLastSet = new BasicAttribute("sambaPwdLastSet",
                    String.valueOf(System.currentTimeMillis() / 1000L));

            ModificationItem[] mods = new ModificationItem[4];
            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);

            DirContext ctx = new InitialDirContext(env);
            ctx.modifyAttributes(buildUserDN(user), 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.olat.ldap.LDAPLoginManagerImpl.java

/**
 * Change the password on the LDAP server.
 * /*from w  w  w  .  j  ava2s. com*/
 * @see org.olat.ldap.LDAPLoginManager#changePassword(org.olat.core.id.Identity, java.lang.String, org.olat.ldap.LDAPError)
 */
@Override
public void changePassword(final Identity identity, final String pwd, final LDAPError errors) {
    final String uid = identity.getName();
    final String ldapUserPasswordAttribute = LDAPLoginModule.getLdapUserPasswordAttribute();
    try {
        final DirContext ctx = bindSystem();
        final String dn = searchUserDN(uid, ctx);

        final ModificationItem[] modificationItems = new ModificationItem[1];

        Attribute userPasswordAttribute;
        if (LDAPLoginModule.isActiveDirectory()) {
            // active directory need the password enquoted and unicoded (but little-endian)
            final String quotedPassword = "\"" + pwd + "\"";
            final char unicodePwd[] = quotedPassword.toCharArray();
            final byte pwdArray[] = new byte[unicodePwd.length * 2];
            for (int i = 0; i < unicodePwd.length; i++) {
                pwdArray[i * 2 + 1] = (byte) (unicodePwd[i] >>> 8);
                pwdArray[i * 2 + 0] = (byte) (unicodePwd[i] & 0xff);
            }
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwdArray);
        } else {
            userPasswordAttribute = new BasicAttribute(ldapUserPasswordAttribute, pwd);
        }

        modificationItems[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, userPasswordAttribute);
        ctx.modifyAttributes(dn, modificationItems);
        ctx.close();
    } catch (final NamingException e) {
        logError("NamingException when trying to change password with username::" + uid, e);
        errors.insert("Cannot change the password");
    }
}