Redis管理平台Cachecloud使用LDAP进行认证登录()

cachecloud版本:https://github.com/sohutv/cachecloud/archive/refs/tags/2.2.tar.gz

公司使用ldap的ssl认证,java本人一点都不懂,耗费几天时间没有搞定,只能曲线救国,使用stunnel做代理连接ldaps,cachecloud连接stunnel的代理端口

stunnel配置:

/etc/stunnel/ldap.conf

[ldap]
client = yes
accept = 127.0.0.1:389
connect = ldap-srv.jpushoa.com:636
CAfile = /etc/openldap/cacerts/cacert.pem
cert = /etc/openldap/cacerts/client.crt
key = /etc/openldap/cacerts/client.key
package com.sohu.cache.login.impl;

import com.sohu.cache.login.LoginComponent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.Hashtable;

import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by yijunzhang
 */
public class DefaultLoginComponent implements LoginComponent {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean passportCheck(String userName, String password) {
       //LDAP登陆地址
        String ldapUrl = "ldap://127.0.0.1:389";
        if (StringUtils.isBlank(ldapUrl)) {
            logger.warn("ldap url is empty!!");
            return true;
        }
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
        env.put("java.naming.provider.url", ldapUrl);
        env.put("java.naming.security.authentication", "simple");
        env.put("java.naming.security.principal", "uid=" + userName + ",ou=people,dc=jpushoa,dc=com");
        env.put("java.naming.security.credentials", password);
        DirContext ctx = null;
        try {
            ctx = new InitialDirContext(env);
            if (ctx != null) {
                return true;
            }
        } catch (Exception e) {
            logger.error("username {} passportCheck: " + e.getMessage(), userName, e);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return false;
    }

        @Override
    public String getEmail(String ticket) {
        return null;
    }

    @Override
    public String getRedirectUrl(HttpServletRequest request) {
        StringBuffer redirectUrl = new StringBuffer();
        redirectUrl.append(request.getSession(true).getServletContext().getContextPath());
        redirectUrl.append("/manage/login?");
        // 跳转地址
        redirectUrl.append("redirectUrl");
        redirectUrl.append("=");
        redirectUrl.append(request.getRequestURI());
        // 跳转参数
        String query = request.getQueryString();
        if (StringUtils.isNotBlank(query)) {
            redirectUrl.append("?");
            try {
                redirectUrl.append(URLEncoder.encode(request.getQueryString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return redirectUrl.toString();
    }

    @Override
    public String getLogoutUrl() {
        return null;
    }
}
/**
     * 用户登录
     *
     * @param userName 用户名
     * @param password 密码
     * @param isAdmin  是否勾选超级管理员选项,1是0否
     * @return
     */
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public ModelAndView loginIn(HttpServletRequest request,
                                HttpServletResponse response, Model model, String userName, String password, boolean isAdmin) {
        // 登录结果
        LoginResult loginResult = new LoginResult();
        loginResult.setAdminEnum((isAdmin == true ? AdminEnum.IS_ADMIN : AdminEnum.NOT_ADMIN));
        loginResult.setLoginEnum(LoginEnum.LOGIN_WRONG_USER_OR_PASSWORD);

        AppUser userModel = null;
        if (ConstUtils.SUPER_ADMIN_NAME.equals(userName)) {
            userModel = userService.getByName(userName);
            if (userModel != null && ConstUtils.SUPER_ADMIN_PASS.equals(password)) {
                loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
            } else {
                loginResult.setLoginEnum(LoginEnum.LOGIN_WRONG_USER_OR_PASSWORD);
            }
        } else {
            if (loginComponent != null && loginComponent.passportCheck(userName, password)) {
                // 同时要验证是否有cachecloud权限
                userModel = userService.getByName(userName);
                if (userModel != null && userModel.getType() != AppUserTypeEnum.NO_USER.value()) {
                    if (isAdmin) {
                        if (AppUserTypeEnum.ADMIN_USER.value().equals(userModel.getType())) {
                            loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
                        } else {
                            loginResult.setLoginEnum(LoginEnum.LOGIN_NOT_ADMIN);
                        }
                    } else {
                        loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
                    }
                } else {
                    // 用户不存在
                    // loginResult.setLoginEnum(LoginEnum.LOGIN_USER_NOT_EXIST);
                    // 用户不存在则插入用户
                    AppUser appUser = new AppUser(userName, userName, userName + "@jiguang.cn", "13500000000", "13500000000", '2', '1');
                   // appUser = new AppUser(user.getName(), user.getChName(), user.getEmail(), user.getMobile(), user.getWeChat(), AppUserTypeEnum.REGULAR_USER.value(), AppUserAlertEnum.YES.value());
                    userService.save(appUser);
                }
            }
        }
        // 登录成功写入登录状态
        if (loginResult.getLoginEnum().equals(LoginEnum.LOGIN_SUCCESS)) {
            userLoginStatusService.addLoginStatus(request, response, userModel.getName());
        }
        model.addAttribute("success", loginResult.getLoginEnum().value());
        model.addAttribute("admin", loginResult.getAdminEnum().value());
        return new ModelAndView();
    }
————————

cachecloud版本:https://github.com/sohutv/cachecloud/archive/refs/tags/2.2.tar.gz

公司使用ldap的ssl认证,java本人一点都不懂,耗费几天时间没有搞定,只能曲线救国,使用stunnel做代理连接ldaps,cachecloud连接stunnel的代理端口

stunnel配置:

/etc/stunnel/ldap.conf

[ldap]
client = yes
accept = 127.0.0.1:389
connect = ldap-srv.jpushoa.com:636
CAfile = /etc/openldap/cacerts/cacert.pem
cert = /etc/openldap/cacerts/client.crt
key = /etc/openldap/cacerts/client.key
package com.sohu.cache.login.impl;

import com.sohu.cache.login.LoginComponent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.util.Hashtable;

import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by yijunzhang
 */
public class DefaultLoginComponent implements LoginComponent {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean passportCheck(String userName, String password) {
       //LDAP登陆地址
        String ldapUrl = "ldap://127.0.0.1:389";
        if (StringUtils.isBlank(ldapUrl)) {
            logger.warn("ldap url is empty!!");
            return true;
        }
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
        env.put("java.naming.provider.url", ldapUrl);
        env.put("java.naming.security.authentication", "simple");
        env.put("java.naming.security.principal", "uid=" + userName + ",ou=people,dc=jpushoa,dc=com");
        env.put("java.naming.security.credentials", password);
        DirContext ctx = null;
        try {
            ctx = new InitialDirContext(env);
            if (ctx != null) {
                return true;
            }
        } catch (Exception e) {
            logger.error("username {} passportCheck: " + e.getMessage(), userName, e);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return false;
    }

        @Override
    public String getEmail(String ticket) {
        return null;
    }

    @Override
    public String getRedirectUrl(HttpServletRequest request) {
        StringBuffer redirectUrl = new StringBuffer();
        redirectUrl.append(request.getSession(true).getServletContext().getContextPath());
        redirectUrl.append("/manage/login?");
        // 跳转地址
        redirectUrl.append("redirectUrl");
        redirectUrl.append("=");
        redirectUrl.append(request.getRequestURI());
        // 跳转参数
        String query = request.getQueryString();
        if (StringUtils.isNotBlank(query)) {
            redirectUrl.append("?");
            try {
                redirectUrl.append(URLEncoder.encode(request.getQueryString(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return redirectUrl.toString();
    }

    @Override
    public String getLogoutUrl() {
        return null;
    }
}
/**
     * 用户登录
     *
     * @param userName 用户名
     * @param password 密码
     * @param isAdmin  是否勾选超级管理员选项,1是0否
     * @return
     */
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public ModelAndView loginIn(HttpServletRequest request,
                                HttpServletResponse response, Model model, String userName, String password, boolean isAdmin) {
        // 登录结果
        LoginResult loginResult = new LoginResult();
        loginResult.setAdminEnum((isAdmin == true ? AdminEnum.IS_ADMIN : AdminEnum.NOT_ADMIN));
        loginResult.setLoginEnum(LoginEnum.LOGIN_WRONG_USER_OR_PASSWORD);

        AppUser userModel = null;
        if (ConstUtils.SUPER_ADMIN_NAME.equals(userName)) {
            userModel = userService.getByName(userName);
            if (userModel != null && ConstUtils.SUPER_ADMIN_PASS.equals(password)) {
                loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
            } else {
                loginResult.setLoginEnum(LoginEnum.LOGIN_WRONG_USER_OR_PASSWORD);
            }
        } else {
            if (loginComponent != null && loginComponent.passportCheck(userName, password)) {
                // 同时要验证是否有cachecloud权限
                userModel = userService.getByName(userName);
                if (userModel != null && userModel.getType() != AppUserTypeEnum.NO_USER.value()) {
                    if (isAdmin) {
                        if (AppUserTypeEnum.ADMIN_USER.value().equals(userModel.getType())) {
                            loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
                        } else {
                            loginResult.setLoginEnum(LoginEnum.LOGIN_NOT_ADMIN);
                        }
                    } else {
                        loginResult.setLoginEnum(LoginEnum.LOGIN_SUCCESS);
                    }
                } else {
                    // 用户不存在
                    // loginResult.setLoginEnum(LoginEnum.LOGIN_USER_NOT_EXIST);
                    // 用户不存在则插入用户
                    AppUser appUser = new AppUser(userName, userName, userName + "@jiguang.cn", "13500000000", "13500000000", '2', '1');
                   // appUser = new AppUser(user.getName(), user.getChName(), user.getEmail(), user.getMobile(), user.getWeChat(), AppUserTypeEnum.REGULAR_USER.value(), AppUserAlertEnum.YES.value());
                    userService.save(appUser);
                }
            }
        }
        // 登录成功写入登录状态
        if (loginResult.getLoginEnum().equals(LoginEnum.LOGIN_SUCCESS)) {
            userLoginStatusService.addLoginStatus(request, response, userModel.getName());
        }
        model.addAttribute("success", loginResult.getLoginEnum().value());
        model.addAttribute("admin", loginResult.getAdminEnum().value());
        return new ModelAndView();
    }