这很棘手。您不能设置未加密的密码,如果您还没有设置所有加密结构,则无法使用 LDAPS,因此您需要使用 Kerberos。
我让它像这样工作:
- 做一个简单的绑定到 AD
- kerberise 你的会话
- 使用密码创建用户帐户,但将其设置为过期)
现在您可以使用普通连接来设置其他属性了。
// KRB5 connection details:
System.setProperty("java.security.krb5.kdc", "domain.com");
String username = "admin@DOMAIN.COM";
String realm = "DOMAIN.COM";
System.setProperty("java.security.krb5.realm", realm);
System.setProperty("java.security.krb5.debug", "true");
System.setProperty("sun.security.krb5.debug", "true");
// standard JNDI LDAP stuff:
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.PROVIDER_URL, "ldap://dc01.domain.com:389");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, "abcd1234");
ctxt = new InitialLdapContext(env, new Control [0]);
// kerberised connection details:
LoginModule module;
module = (LoginModule) Class.forName("com.sun.security.auth.module.Krb5LoginModule").newInstance();
Subject subject = new Subject();
Map<String, String> options = new HashMap<String, String>();
Map<String, Object> sharedState = new HashMap<String, Object>();
sharedState.put("javax.security.auth.login.password", properties.getProperty("ad.passwd").toCharArray());
sharedState.put("javax.security.auth.login.name", username);
options.put("principal", username);
options.put("storeKey", "true");
options.put("useFirstPass", "true");
options.put("debug", "true");
module.initialize(subject, null, sharedState, options);
module.login();
module.commit();
// now create a user account:
Subject.doAs(svc.getSubject(), new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
try {
String password = "\"Password1\"";
final Hashtable<String, String> env = svc.getEnvironment();
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
LdapContext ctxt = new InitialLdapContext(env, new Control[0]);
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new
ModificationItem(DirContext.REPLACE_ATTRIBUTE, new
BasicAttribute("userPassword", password.getBytes("UTF-16LE")));
ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED)));
ctxt.modifyAttributes(dn, mods);
}
catch (NamingException e) {
System.out.println("Failed to set password.");
e.printStackTrace();
}
return null;
}
});
现在您可以正常更改其他设置了。
希望对您有所帮助。
吉姆