Skip to content

Instantly share code, notes, and snippets.

@vegaasen
Last active April 8, 2022 19:23
Show Gist options
  • Save vegaasen/64053b6cdff9472c3e7b765e3de91a39 to your computer and use it in GitHub Desktop.
Save vegaasen/64053b6cdff9472c3e7b765e3de91a39 to your computer and use it in GitHub Desktop.
Unlock user in AD using java and UnBoundID :-)
/**
* Simplifies the process of unlocking users.
* <p>
* The AD attribute "userAccountControl" may be any of the following
* - 512 Enabled Account (normally this..)
* - 514 Disabled Account
* - 544 Enabled, Password Not Required
* - 546 Disabled, Password Not Required
* - 66048 Enabled, Password Doesn't Expire
* - 66050 Disabled, Password Doesn't Expire
* - 66080 Enabled, Password Doesn't Expire & Not Required
* - 66082 Disabled, Password Doesn't Expire & Not Required
* <p>
* The AD attribute "lockoutTime" must be set to "0" in order to successfully unlock the user itself
*
* @author <a href="mailto:vegaasen@gmail.com">vegaasen</a>
* @version 08.02.2017
* @since 08.02.2017
*/
private static void unlock(String username) {
try {
SearchResult result = ldapConnection.search(new SearchRequest(PROPERTIES.getProperty("ldap.base.dn"), SearchScope.SUB, String.format("(sAMAccountName=%s*)", username.toLowerCase()), SearchRequest.ALL_USER_ATTRIBUTES));
if (!CollectionUtils.hasElements(result.getSearchEntries())) {
return;
}
DN candidateDn = result.getSearchEntries().iterator().next().getParsedDN();
ModifyRequest modifyRequest = new ModifyRequest(candidateDn, assembleReplaceModification("userAccountControl", "512"));
assembleReplaceModification(modifyRequest, "lockoutTime", "0");
LDAPResult modifyResult = ldapConnection.modify(modifyRequest);
if (modifyResult.getResultCode().equals(ResultCode.SUCCESS)) {
LOG.info(String.format("Successfully unlocked user {%s} from {%s}", candidateDn, new Date()));
}
} catch (Exception e) {
LOG.log(Level.WARNING, String.format("Unable to modify {%s}", username), e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment