码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA修改AD域密码_免证书认证

时间:2020-03-04 14:49:02      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:pre   osi   res   ram   ast   sls   端口   tst   targe   

更改用户账户密码,必须要使用ssl方式登录到AD。

网上大部分教程使用TrustStore的方式连接, 

        Hashtable env = new Hashtable();
        System.setProperty("javax.net.ssl.trustStore", KEYSTORE);
        System.setProperty("javax.net.ssl.trustStorePassword", KEYSTORE_PWD);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ADMIN_NAME);
        env.put(Context.SECURITY_CREDENTIALS, ADMIN_PASSWORD);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put(Context.PROVIDER_URL, LDAP_SSL_URL);
try {
            ctx =  new InitialLdapContext(env, null);//new InitialDirContext(HashEnv);// 初始化上下文
        } catch (AuthenticationException e) {
            System.out.println("身份验证失败!"+e.toString());
            e.printStackTrace();
        } catch (CommunicationException e) {
            System.out.println("AD域连接失败!"+e.toString());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("身份验证未知异常!"+e.toString());
            e.printStackTrace();
        } finally{
            return ctx;
        }  

 

最后ssl连接失败,报如下错误:javax.naming.CommunicationException: simple bind failed: xxxx:636 [Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]。

也有部分教程提到了绕过ssl的方式,但是都只有部分代码,直到遇到了这段代码

原地址:JAVA修改AD域密码_免证书

下载地址:JNDI免证书推送AD域密码.zip

 

完整代码如下:

package org.util.ad;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.SortControl;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;

public class LdapSSLUtil {
    private final static String adminName = "xxx";
    private final static String adminPassword = "xxxx";
    private final String ldapURL = "LDAPS://xxx.xxx.xxx:636";   //注意,必须使用域名加636端口
    private final String factory = "com.sun.jndi.ldap.LdapCtxFactory";
    private final String BASEN = "OU=xx,DC=xx,DC=xx";
    private LdapContext ctx = null;

    private final Control[] sortConnCtls = new SortControl[1];


    /**
     * 用户认证
     *
     * @param userName
     * @param password
     */
    public void ldap_connect(String userName, String password) {


        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, userName);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, ldapURL);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put("java.naming.ldap.factory.socket", "org.util.ad.DummySSLSocketFactory");


        try {

            // 初始化ldapcontext,方式1
//            ctx = new InitialLdapContext(env, null);
            //方式2
            sortConnCtls[0] = new SortControl("sAMAccountName", Control.CRITICAL);
            ctx = new InitialLdapContext(env, sortConnCtls);

            System.out.println("认证成功");
        } catch (Exception e) {
            System.out.println("认证失败");
            e.printStackTrace();
        }
    }

    //关闭连接
    public void close_connect() {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查找用户信息
     *
     * @param cn
     * @return
     */
    public Attributes getUser(String cn) {
        Attributes attrs = null;
        SearchControls contro = new SearchControls();
        contro.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try {
            //有的企业员工的dn不是有cn开头的,而是由uid开头的,这个因企业而异
            //使用cn,若存在重名用户,则返回的是最后一个员工,存在bug
//            NamingEnumeration<SearchResult> en = ctx.search(BASEN, "cn=" + cn, contro);
            //使用sAMAccountName,避免重名,比如存在四个张伟
            NamingEnumeration<SearchResult> en = ctx.search(BASEN, "sAMAccountName=" + cn, contro);
            if (en == null || !en.hasMoreElements()) {
                System.out.println("未找到该用户:" + cn);
                return null;
            }
            while (en.hasMoreElements()) {
                Object obj = en.nextElement();
                if (obj instanceof SearchResult) {
                    SearchResult si = (SearchResult) obj;
                    attrs = si.getAttributes();
                    //attrs是用户的一些相关属性,一些很重要的属性
                    System.out.println(attrs);
                }
            }
        } catch (NamingException e) {
            System.out.println("查找用户异常。。。");
            e.printStackTrace();
        }
        return attrs;
    }

    /**
     * 获取用户的dn
     *
     * @param cn
     * @return
     */
    public String getUserDN(String cn) {
        Attributes attrs = getUser(cn);
        //distinguishedname这个属性即是用户的dn,可以打印看看
        String userDN = attrs.get("distinguishedname").toString().split(":")[1].trim();
        return userDN;
    }

    //解锁账号和下次登录需要修改密码
    public void enableUser(String userName) {
        String userDN = getUserDN(userName);
        BasicAttributes attrsbu = new BasicAttributes();

        //这个是重点,下面有话有说
        attrsbu.put("userAccountControl", "512");
        attrsbu.put("pwdLastSet", "0");

        try {
            ctx.modifyAttributes(userDN, DirContext.REPLACE_ATTRIBUTE, attrsbu);
            System.out.println("解锁账号成功");
        } catch (NamingException e) {
            System.out.println("解锁账号失败");
            e.printStackTrace();
        }
    }

    //重置密码
    public void updateUserPassword(String cn, String newPassword) throws
            UnsupportedEncodingException, NamingException {

        ModificationItem[] mods = new ModificationItem[1];

        String newQuotedPassword = "\"" + newPassword + "\"";

        byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");

        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,

                new BasicAttribute("unicodePwd", newUnicodePassword));

        // 修改密码
        String userDN = getUserDN(cn);
        ctx.modifyAttributes(userDN, mods);

    }

    /**
     * AD账户时间戳转换
     * @param accountExpiresL
     * @return
     */
    public static Date adExpiresToDate(long accountExpiresL){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(1601, 0, 1, 0, 0);
        accountExpiresL = accountExpiresL/ 10000 + calendar.getTime().getTime();
        return new Date(accountExpiresL);
    }

    /**
     * 获取AD账户失效日期
     * @param account
     * @return
     */
    public  Date getAccountExpiresToDate(String account){
        Attributes attrs = getUser(account);
        //distinguishedname这个属性即是用户的dn,可以打印看看
        String accountexpires = attrs.get("accountexpires").toString().split(":")[1].trim();
//        return accountexpires;
        System.out.println(accountexpires);
        Long expiresLong = Long.parseLong(accountexpires);
        Date expiresDate  = adExpiresToDate(expiresLong);
        System.out.println(expiresDate);
        return expiresDate;
    }

    /**
     * 上次密码修改时间
     * @param account
     * @return
     */
    public Date getPwdLastSetTime(String account){
        Attributes attrs = getUser(account);
        //distinguishedname这个属性即是用户的dn,可以打印看看
        String pwdlastset = attrs.get("pwdlastset").toString().split(":")[1].trim();
//        return accountexpires;
        System.out.println(pwdlastset);
        Long pwdlastsetLong = Long.parseLong(pwdlastset);
        Date pwdLastSetDate  = adExpiresToDate(pwdlastsetLong);
        System.out.println(pwdLastSetDate);
        return pwdLastSetDate;
    }

    public static void main(String[] args)throws Exception{
        LdapSSLUtil ldapUtil = new LdapSSLUtil();
        ldapUtil.ldap_connect(adminName, adminPassword);
        String account = "xxx";
        //重置密码
        ldapUtil.updateUserPassword(account,"xxxx");
        ldapUtil.getUserDN(account);
        ldapUtil.getAccountExpiresToDate(account);
        ldapUtil.getPwdLastSetTime(account);
        
        ldapUtil.close_connect();

    }
}

 

参考:

https://blog.csdn.net/xuxiaoqun0_0/article/details/82052218

https://blogs.msdn.microsoft.com/alextch/2012/05/15/how-to-set-active-directory-password-from-java-application/

https://www.iteye.com/blog/chnic-2065877

https://my.oschina.net/haison/blog/678354?p={{page}}

https://blog.csdn.net/laxsong/article/details/51344002

https://www.cnblogs.com/sunjiguang/p/9257585.html

https://www.bbsmax.com/A/q4zVZ0nGzK/

https://www.cnblogs.com/nidongde/p/5364622.html

https://blog.csdn.net/hc1017/article/details/81293323?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

https://blog.csdn.net/qq_41207282/article/details/97133887#comments

https://blog.csdn.net/hct368/article/details/97247258

https://www.cnblogs.com/amoyzhu/p/9259264.html

https://blog.51cto.com/gaowenlong/1969586

https://blog.51cto.com/gaowenlong/1969585

 

JAVA修改AD域密码_免证书认证

标签:pre   osi   res   ram   ast   sls   端口   tst   targe   

原文地址:https://www.cnblogs.com/huanghongbo/p/12409209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!