QueryDatabaseLDAPAuthenticationHandler.java 5.17 KB
/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License.  You may obtain a
 * copy of the License at the following location:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.jasig.cas.adaptors.ldap;

import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
import org.jasig.cas.authentication.handler.AuthenticationException;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import weaver.loginsso.AES;

import javax.naming.Context;
import javax.naming.directory.InitialDirContext;
import java.util.Hashtable;
import java.util.List;

/**
 * Created by crazyDream on 2018/10/8.
 * LDAP验证
 */
public class QueryDatabaseLDAPAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {


    protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials) throws AuthenticationException {
        return false;
    }

    /**
     * LDAP验证逻辑
     *
     * @param credentials
     * @return
     * @throws AuthenticationException
     */
    public final boolean authenticateUsernamePasswordLDAP(final UsernamePasswordCredentials credentials, String oaUid, SimpleJdbcTemplate jdbcTemplate) throws AuthenticationException {
        final String username = getPrincipalNameTransformer().transform(credentials.getUsername());
        final String password = credentials.getPassword();
        try {
            return authentic(username, password, oaUid, jdbcTemplate);
        } catch (final IncorrectResultSizeDataAccessException e) {
            return false;
        }
    }


    public boolean authentic(String loginid, String password, String oaUid, SimpleJdbcTemplate jdbcTemplate) {
        try {
            LdapService ldapService = new LdapService();
            List<LdapSyncDataBean> userDatas = ldapService.getSyncDatasByOAIDDataType("" + oaUid, "3", jdbcTemplate);
            if (null == userDatas || userDatas.size() == 0) {
                log.error("AuthenticUtil>authentic()>账号不存在" + loginid + ":" + oaUid);
                return false;
            }

            String ldapId = userDatas.get(0).getLdapId();
            LdapBaseBean baseBean = ldapService.queryByLdapId(ldapId, jdbcTemplate);
            if (baseBean == null) {
                log.error(String.format("未找到对应的LDAP配置(%s)", ldapId));
                return false;
            } else if (baseBean.getIsUsed() == 0) {
                log.error(String.format("Ldap未开启(%s)", ldapId));
                return false;
            } else if (baseBean.getIsAdAccount() == 0) {

                log.error(String.format("LDAP登录认证未启用(%s)", ldapId));
                return false;
            }


            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, baseBean.getFactoryClass());
            env.put(Context.PROVIDER_URL, String.format("%s://%s:%s", baseBean.getProtocol(), baseBean.getIp(), baseBean.getPort()));
            env.put(Context.SECURITY_PRINCIPAL, userDatas.get(0).getRdn());
            env.put(Context.SECURITY_CREDENTIALS, getDecryptPassword(password));
            env.put(Context.REFERRAL, "ignore");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put("ignorepartialresultexception", "true");

            if ("ldaps".equalsIgnoreCase(baseBean.getProtocol())) {
                env.put(Context.SECURITY_PROTOCOL, "ssl");

                if (baseBean.getPassingCert() == 1) {
                    env.put("java.naming.ldap.factory.socket", "com.weaver.integration.ldap.util.passingCert.DummySSLSocketFactory");
                } else {
                    System.setProperty("javax.net.ssl.trustStore", baseBean.getKeystorePath());
                    System.setProperty("javax.net.ssl.trustStorePassword", baseBean.getKeystorePassword());
                }
            }

            InitialDirContext initialContext = new InitialDirContext(env);
            initialContext.close();
        } catch (Exception e) {
            log.error("AuthenticUtil>authentic()>认证异常" + loginid, e);
            return false;
        }
        return true;
    }


    private String getDecryptPassword(String password) {
        String yjcust = AES.decrypt(password, "yjcust");
        if (yjcust != null && yjcust.indexOf("-f-g-") > 0) {
            password = yjcust.substring(0, yjcust.indexOf("-f-g-"));
        }
        return password;
    }


}