用JAVA通过JNDI操作活动目录(AD)中LDAP

    

      由于SSO和账号同步,都会使用到AD。这里我就使用JAVA语言直接调用AD中用户信息,进行常见的认证,增加,修改

 

和删除操作。

 

一、获取AD的SSL连接

/** * 从连接池中获取一个连接. * * @return LdapContext * @throws NamingException */ 
public LdapContext getConnectionFromFool() throws NamingException { 
    String keystore = "F://utrust//jdk1.6.0//jre//lib//security//cacerts"; 
    System.setProperty("javax.net.ssl.trustStore", keystore); 
    Properties env = new Properties(); 
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 
    env.put(Context.PROVIDER_URL, "ldap://192.168.0.190:636"); 
    env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
    env.put(Context.SECURITY_PRINCIPAL, "cn=Administrator,cn=Users,dc=all,dc=com"); 
    env.put(Context.SECURITY_CREDENTIALS, "123456"); 
    env.put(Context.SECURITY_PROTOCOL, "ssl"); 
    env.put("com.sun.jndi.ldap.connect.pool", "true"); 
    env.put("java.naming.referral", "follow"); 
    return new InitialLdapContext(env, null); 
}

 

 

二、认证用户信息

/**
 * 校验用户登录. * * @param userDn * String * @param password * String * @return boolean
 */
public boolean authenticate(String userDn, String password) {
    LdapContext ctx = null;
    try {
        Control[] connCtls = new Control[]{};
        ctx = getConnectionFromFool();
        ctx.getRequestControls();
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(connCtls);
        return true;
    } catch (AuthenticationException e) {
        return false;
    } catch (NamingException e) {
        return false;
    } finally {
        if (ctx != null) {
            try {
                ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, transientInstance.getAccountName());
                ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, transientInstance.getAccountPwd());
                ctx.reconnect(ctx.getConnectControls());
                ctx.close();
            } catch (NamingException e) { // TODO Auto-generated catch block 
                 e.printStackTrace(); 
                
            }                 
            ctx = null; 
        } 
    } 
}

 

 

三、添加用户信息

/** * 添加用户. * * @param userDN * String用户DN * @param userName * String 用户登录名 * @param userPwd * String 用户密码 * @return boolean 添加是否成功. * */ public boolean addUser(String userDN, String userName, String userPwd) { LdapContext ctx = null; try { ctx = getConnectionFromFool(); // Create attributes to be associated with the new user Attributes attrs = new BasicAttributes(true); // These are the mandatory attributes for a user object // Note that Win2K3 will automagically create a random // samAccountName if it is not present. (Win2K does not) attrs.put("objectClass", "user"); attrs.put("sAMAccountName", userName); attrs.put("cn", userName); // some useful constants from lmaccess.h int UF_ACCOUNTDISABLE = 0x0002; int UF_PASSWD_NOTREQD = 0x0020; int UF_NORMAL_ACCOUNT = 0x0200; int UF_PASSWORD_EXPIRED = 0x800000; // Note that you need to create the user object before you can // set the password. Therefore as the user is created with no // password, user AccountControl must be set to the following // otherwise the Win2K3 password filter will return error 53 // unwilling to perform. attrs.put("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_ACCOUNTDISABLE)); // Create the context ctx.createSubcontext(userDN, attrs); ModificationItem[] mods = new ModificationItem[2]; // Replace the "unicdodePwd" attribute with a new value // Password must be both Unicode and a quoted string String newQuotedPassword = "/"" + userPwd + "/""; byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE"); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword)); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer .toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED))); // Perform the update ctx.modifyAttributes(userDN, mods); mods = null; return true; } catch (NamingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ctx = null; } } return false; }

或者:

/** * 添加用户. * * @param userDN * String用户DN * @param attrs * Attributes 用户属性 * @return boolean 添加是否成功. * */ public boolean addUser(String userDN, Attributes attrs) { LdapContext ctx = null; try { ctx = getConnectionFromFool(); String userName = (String) attrs.get("cn").get(); if (userName == null || "".equals(userName)) { return false; } // Replace the "unicdodePwd" attribute with a new value // Password must be both Unicode and a quoted string if (attrs.get("objectClass") == null || attrs.get("objectClass").get() == null) { attrs.put("objectClass","user"); } if (attrs.get("sAMAccountName") == null || attrs.get("sAMAccountName").get() == null) { attrs.put("sAMAccountName", userName); } if (attrs.get("userAccountControl") == null || attrs.get("userAccountControl").get() == null) { int UF_ACCOUNTDISABLE = 0x0002; int UF_PASSWD_NOTREQD = 0x0020; int UF_NORMAL_ACCOUNT = 0x0200; int UF_PASSWORD_EXPIRED = 0x800000; attrs.put("userAccountControl", Integer .toString(UF_NORMAL_ACCOUNT + UF_PASSWD_NOTREQD + UF_PASSWORD_EXPIRED + UF_ACCOUNTDISABLE)); } String userPwd = (String) attrs.get("unicodePwd").get(); attrs.remove(pwd_index); // Create the context ctx.createSubcontext(userDN, attrs); // 添加用户密码 if (userPwd != null) { int UF_NORMAL_ACCOUNT = 0x0200; int UF_PASSWORD_EXPIRED = 0x800000; ModificationItem[] mods = new ModificationItem[2]; String newQuotedPassword = "/"" + userPwd + "/""; byte[] newUnicodePassword = newQuotedPassword .getBytes("UTF-16LE"); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(pwd_index, newUnicodePassword)); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer .toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED))); // Perform the update ctx.modifyAttributes(userDN, mods); } return true; } catch (NamingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ctx = null; } } return false; }

 

 

 

四、修改用户信息

/** * 修改用户信息. * * @param attrs * Attributes 需要修改的用户属性. * @param userDN * String 用户DN * @return */ public boolean modify(Attributes attrs, String userDN) { LdapContext ctx = null; try { ctx = getConnectionFromFool(); attrs.remove(key_index); ctx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrs); return true; } catch (NamingException e) { System.err.println("Problem changing password: " + e); } catch (Exception e) { System.err.println("Problem: " + e); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ctx = null; } } return false; }

 

五、删除用户信息

/** * 删除用户. * * @param userDN * String 用户DN * @return */ public boolean del(String userDN) { LdapContext ctx = null; try { ctx = getConnectionFromFool(); ctx.destroySubcontext(userDN); return true; } catch (NamingException e) { System.err.println("Problem changing password: " + e); } catch (Exception e) { System.err.println("Problem: " + e); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ctx = null; } } return false; }

 

 

 

变量补充:

 

/**

* 用户的objectClass

*/

super.default_objectclass = "user";

 

/**

* 用户的默认根DN.

*/

super.default_base = "CN=Users,DC=all,DC=com";

 

/**

* 用户默认主键.

*/

super.key_index = "CN";

 

/**

* 用户默认密码属性.

*/

super.pwd_index = "unicodePwd";

 

 

 

/**

* LDAP连接同步配置对象.

*/

 

protected DataSourceConnectLDAPVO transientInstance = null;

 

其中DataSourceConnectLDAPVO类中属性为:

/** * 数据源名. */ private String dataSourceName; /** * 数据源类型. 只有4个值,分别为:0表示“DB” (即关系型数据库), 1表示“AD” (即AD域), 2表示“LDAP”, * 3表示“DOMINO”, 默认为0。. */ private int dataBaseType = 0; /** * 数据源地址. */ private String dataSourceAddress; /** * 数据源端口,默认389. */ private int dataSourcePort = 389; /** * 账号. */ private String accountName; /** * 密码. */ private String accountPwd; /** * userSSL. 只有2个值, 分别为: 0表示false(即不使用userSSL), 1表示true(即使用userSSL), 默认为0。 */ private int isUserSSL = 0; /** * 密钥路径. */ private String secretKeyPath; /** * 访问协议. 只有3个值, 分别为: 0表示“LDAP V3”, 1表示“LDAP V2”, 2表示“DSML V2”, 默认为0。 */ private int protocol = 0; /** * DMSL服务. */ private String dmslService; /** * authenschema. 只有5个值, 分别为: 0表示“SIMPLE”, 1表示“NONE”, 2表示“GSSAPI”, * 3表示“DIGEST-MD5”, 4表示“CRAM-MD5”, 默认为0。 */ private int authenSchema = 0; /** * 根DN. */ private String rootDN; /** * 过滤条件. */ private String filterCondition; /** * 级别. 只有6个值,分别为: 0表示“User + Password”, 1表示“Anonymous”, 2表示“SSL + * Anonymous”, 3表示“SSL + User + Password”, 4表示“SSL + SASL + Keystore * Password”, 5表示“GSSAPI”, 默认为0。 */ private int level = 0; /** * 用户名属性. */ private String userLoginNameAttr; /** * 最大活动数量. */ private int maxActiveValue = 10; /** * 最大. */ private int minValue = 0; /** * 最小. */ private int maxValue = 5; 

 

 

 

 

 

 

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值