Parcourir la source

AD域登录改造

yuanzhi_kuang il y a 1 jour
Parent
commit
f0f0b8ca89

+ 61 - 0
GDYSL/src/com/kingdee/bos/sso/client/filter/ConfigAddressUtil.java

@@ -0,0 +1,61 @@
+package com.kingdee.bos.sso.client.filter;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Properties;
+import org.apache.commons.configuration.ConfigurationException;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.log4j.Logger;
+
+public class ConfigAddressUtil {
+    private static Logger logger = Logger.getLogger(ConfigAddressUtil.class);
+    static Properties prop = null;
+
+
+
+    public static void getProperties() {
+        String configFilePath = System.getProperty("eas.properties.dir") + "/adSsoConfig.properties";
+        logger.info("配置文件路径:" + configFilePath);
+        System.out.println("配置文件路径:" + configFilePath);
+        File configFile = new File(configFilePath);
+        prop = new Properties();
+        FileInputStream fin = null;
+
+        try {
+            fin = new FileInputStream(configFile);
+            PropertiesConfiguration config = new PropertiesConfiguration();
+            config.load(fin, "UTF-8");
+            prop.setProperty("authUrl", config.getString("authUrl"));
+            prop.setProperty("tokenUrl", config.getString("tokenUrl"));
+            prop.setProperty("refreshTokenUrl", config.getString("refreshTokenUrl"));
+            prop.setProperty("client_id", config.getString("client_id"));
+            prop.setProperty("client_secret", config.getString("client_secret"));
+            prop.setProperty("url", config.getString("shrUrl"));
+            prop.setProperty("userUrl", config.getString("userUrl"));
+            prop.setProperty("dataCenter", config.getString("dataCenter"));
+            prop.setProperty("locale", config.getString("locale"));
+            prop.setProperty("mobileEid", config.getString("mobileEid"));
+        } catch (FileNotFoundException var16) {
+            logger.error("ConfigAddressUtil.....FileNotFoundException ", var16);
+        } catch (IOException var17) {
+            logger.error("ConfigAddressUtil.....IOException ", var17);
+        } catch (ConfigurationException var18) {
+            logger.error("ConfigAddressUtil.....ConfigurationException ", var18);
+        } finally {
+            try {
+                fin.close();
+            } catch (IOException var15) {
+                logger.error("ConfigAddressUtil.....IOException ", var15);
+            }
+
+        }
+
+    }
+
+    public static String getProperty(String fileName) {
+        getProperties();
+        return prop.getProperty(fileName);
+    }
+}

+ 472 - 0
GDYSL/src/com/kingdee/bos/sso/client/filter/authentication/KDPortalAuthenticationFilter.java

@@ -0,0 +1,472 @@
+package com.kingdee.bos.sso.client.filter.authentication;
+
+import com.kingdee.bos.BOSException;
+import com.kingdee.bos.Context;
+import com.kingdee.bos.dao.IObjectValue;
+import com.kingdee.bos.metadata.entity.EntityViewInfo;
+import com.kingdee.bos.metadata.entity.FilterInfo;
+import com.kingdee.bos.metadata.entity.FilterItemInfo;
+import com.kingdee.bos.metadata.query.util.CompareType;
+import com.kingdee.bos.sso.client.util.CommonUtils;
+import com.kingdee.bos.sso.client.util.ConfigAddressUtil;
+import com.kingdee.bos.sso.client.util.FilterUtil;
+import com.kingdee.bos.sso.client.util.StringUtil;
+import com.kingdee.eas.base.myeas.PrivacyStatementCustomCollection;
+import com.kingdee.eas.base.myeas.PrivacyStatementCustomFactory;
+import com.kingdee.eas.base.myeas.PrivacyStatementCustomInfo;
+import com.kingdee.eas.base.myeas.PrivacyStatementFactory;
+import com.kingdee.eas.base.usermonitor.IUserMonitor;
+import com.kingdee.eas.base.usermonitor.UserMonitorFactory;
+import com.kingdee.eas.base.usermonitor.UserMonitorSessionInfo;
+import com.kingdee.eas.cp.common.web.util.WebContextUtil;
+import com.kingdee.eas.cp.eip.sso.qrcode.helper.QrCodeTokenHelper;
+import com.kingdee.util.StringUtils;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.jasig.cas.client.Protocol;
+import org.jasig.cas.client.authentication.AuthenticationRedirectStrategy;
+import org.jasig.cas.client.authentication.ContainsPatternUrlPatternMatcherStrategy;
+import org.jasig.cas.client.authentication.DefaultAuthenticationRedirectStrategy;
+import org.jasig.cas.client.authentication.DefaultGatewayResolverImpl;
+import org.jasig.cas.client.authentication.EntireRegionRegexUrlPatternMatcherStrategy;
+import org.jasig.cas.client.authentication.ExactUrlPatternMatcherStrategy;
+import org.jasig.cas.client.authentication.GatewayResolver;
+import org.jasig.cas.client.authentication.RegexUrlPatternMatcherStrategy;
+import org.jasig.cas.client.authentication.UrlPatternMatcherStrategy;
+import org.jasig.cas.client.configuration.ConfigurationKeys;
+import org.jasig.cas.client.util.AbstractCasFilter;
+import org.jasig.cas.client.validation.Assertion;
+
+public class KDPortalAuthenticationFilter extends AbstractCasFilter {
+    private boolean getServerNameFromRequest;
+    private boolean getServerLoginUrlFromRequest;
+    private String serverLoginUrl;
+    private String casServerLoginUrl;
+    private boolean renew;
+    private boolean gateway;
+    private String method;
+    private GatewayResolver gatewayStorage;
+    private AuthenticationRedirectStrategy authenticationRedirectStrategy;
+    private static final Map<String, Class<? extends UrlPatternMatcherStrategy>> PATTERN_MATCHER_TYPES = new HashMap();
+
+    static {
+        PATTERN_MATCHER_TYPES.put("CONTAINS", ContainsPatternUrlPatternMatcherStrategy.class);
+        PATTERN_MATCHER_TYPES.put("REGEX", RegexUrlPatternMatcherStrategy.class);
+        PATTERN_MATCHER_TYPES.put("FULL_REGEX", EntireRegionRegexUrlPatternMatcherStrategy.class);
+        PATTERN_MATCHER_TYPES.put("EXACT", ExactUrlPatternMatcherStrategy.class);
+    }
+
+    public KDPortalAuthenticationFilter() {
+        this(Protocol.CAS2);
+    }
+
+    protected KDPortalAuthenticationFilter(Protocol protocol) {
+        super(protocol);
+        this.renew = false;
+        this.gateway = false;
+        this.gatewayStorage = new DefaultGatewayResolverImpl();
+        this.authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
+    }
+
+    public void init() {
+        super.init();
+        String message = String.format("one of %s and %s must not be null.", ConfigurationKeys.CAS_SERVER_LOGIN_URL.getName(), ConfigurationKeys.CAS_SERVER_URL_PREFIX.getName());
+        CommonUtils.assertNotNull(this.casServerLoginUrl, message);
+    }
+
+    public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+        HttpServletRequest request = (HttpServletRequest)servletRequest;
+        HttpServletResponse response = (HttpServletResponse)servletResponse;
+        if (this.isRequestUrlExcluded(request)) {
+            this.logger.debug("Request is ignored.");
+            filterChain.doFilter(request, response);
+        } else {
+            boolean sessionRenew = false;
+            String userNum = "";
+            HttpSession session = request.getSession(false);
+            String servletPath = request.getServletPath();
+            String assignmentId = request.getParameter("AssignmentId");
+            this.logger.info("doFilter..........判断是否移动端:servletPath{} ", servletPath);
+            this.logger.info("doFilter..........assignmentId{} ", assignmentId);
+            String isAdauth = String.valueOf(request.getSession(false).getAttribute("isAdauth"));
+            String password = request.getParameter("password");
+            String kdacctoken = request.getParameter("kdacctoken");
+            this.logger.info("doFilter..........isAdauth{} ", isAdauth);
+            this.logger.info("doFilter..........password{} ", password);
+            this.logger.info("doFilter..........kdacctoken{} ", kdacctoken);
+            boolean flag = false;
+            if ("/web_frame/easrpc/loginCheck.action".equals(servletPath) && (!StringUtils.isEmpty(password) || StringUtils.isEmpty(kdacctoken))) {
+                flag = true;
+            }
+
+            if ("/shr/msf/service.do".equals(servletPath) || "/web_frame/easrpc/login.do".equals(servletPath)) {
+                flag = true;
+            }
+
+            if ("/mulLan.do".equals(request.getServletPath())) {
+                flag = true;
+            }
+
+            if (!"true".equals(isAdauth) && "/home.do".equals(servletPath)) {
+                flag = true;
+            }
+
+            if ("/adsso".equals(servletPath)) {
+                flag = false;
+            }
+
+            String username = request.getParameter("kdacccode");
+            this.logger.info("doFilter..........进入移动端2:username1{} ", username);
+            if (StringUtils.isEmpty(username)) {
+                username = request.getParameter("username");
+            }
+
+            if (StringUtils.isEmpty(username)) {
+                username = request.getParameter("usern");
+            }
+
+            this.logger.info("doFilter..........进入移动端2:username2{} ", username);
+            Assertion assertion;
+            String serviceUrl;
+            if (username != null) {
+                HttpSession httpSession = request.getSession(false);
+                assertion = httpSession != null ? (Assertion)httpSession.getAttribute("_const_cas_assertion_") : null;
+                if (assertion != null) {
+                    username = URLDecoder.decode(username, "UTF-8");
+                    this.logger.info("doFilter..........进入移动端2:username3{} ", username);
+                    serviceUrl = assertion.getPrincipal().getName();
+                    userNum = serviceUrl;
+                    this.logger.info("doFilter..........进入移动端2:ctxUsername{} ", serviceUrl);
+                    this.logger.info("doFilter..........进入移动端2:userNum{} ", serviceUrl);
+                    if (serviceUrl != null && !serviceUrl.equalsIgnoreCase(username)) {
+                        httpSession.setAttribute("_const_cas_assertion_", (Object)null);
+                        httpSession.setAttribute("KD_PORTAL_IS_INIT_CONTEXT", (Object)null);
+                        httpSession.invalidate();
+                        sessionRenew = true;
+                    }
+
+                    if (httpSession.getAttribute("userMonitorSessionInfo") != null) {
+                        UserMonitorSessionInfo userMonitorSessionInfo = (UserMonitorSessionInfo)httpSession.getAttribute("userMonitorSessionInfo");
+
+                        try {
+                            IUserMonitor iUserMonitor = UserMonitorFactory.getRemoteInstance();
+                            IObjectValue info = iUserMonitor.getValue(userMonitorSessionInfo.getId());
+                            if (info == null) {
+                                httpSession.setAttribute("_const_cas_assertion_", (Object)null);
+                                httpSession.setAttribute("KD_PORTAL_IS_INIT_CONTEXT", (Object)null);
+                                httpSession.invalidate();
+                                sessionRenew = true;
+                            }
+                        } catch (Exception var26) {
+                            this.logger.error("checkUserBeTicked err!", var26);
+                        }
+                    }
+                }
+            }
+
+            String queryString;
+            String requestURL;
+            String constructServerName;
+            String userNumber;
+            String urlToRedirectTo;
+            if ("/webviews/workflow/transferApprove.jsp".equals(servletPath)) {
+                constructServerName = request.getHeader("user-agent");
+                this.logger.info("doFilter..........进入移动端2:requestHeader{} ", constructServerName);
+                int type = this.getDeviceType(constructServerName);
+                serviceUrl = null;
+                userNumber = "";
+                if (session != null) {
+                    Object userNumberObject = session.getAttribute("userNumber");
+                    if (userNumberObject != null) {
+                        userNumber = (String)userNumberObject;
+                    }
+                }
+
+                this.logger.info("doFilter..........进入移动端2:userNumber{} ", userNumber);
+                if (type == 1 || type == 2) {
+                    this.logger.info("doFilter..........进入移动端2.getDeviceType:type{} ", type);
+                    this.logger.info("doFilter..........进入移动端2.getDeviceType:userNum{} ", userNum);
+                    Map<String, String> param2 = new HashMap();
+                    param2.put("assignmentId", assignmentId);
+                    session.setAttribute("assignment", param2);
+                    if (!StringUtils.isEmpty(userNumber)) {
+                        urlToRedirectTo = ConfigAddressUtil.getProperty("url");
+                        queryString = ConfigAddressUtil.getProperty("mobileEid");
+                        requestURL = urlToRedirectTo + "/index2.do?eid=" + queryString + "&appid=10036&param=" + userNumber;
+                        this.logger.info("doFilter.......进入移动端2...redirect{} ", requestURL);
+                        response.sendRedirect(requestURL);
+                    }
+                }
+            }
+
+            this.logger.info("doFilter..........不跳移动端2:{} ", servletPath);
+            this.setEncodeServiceUrl(true);
+            this.constructLoginUrl(servletRequest, sessionRenew);
+            constructServerName = this.constructServerName(servletRequest);
+            assertion = session != null ? (Assertion)session.getAttribute("_const_cas_assertion_") : null;
+            if (assertion != null) {
+                serviceUrl = request.getHeader("x-requested-with");
+                if (!"XMLHttpRequest".equals(serviceUrl) && this.checkIsNeedPirvacyStatement(request)) {
+                    this.logger.info("xrequestedwith......{}", serviceUrl);
+                    this.logger.info("request......{}", request);
+                    userNumber = this.constructServiceUrl(request, response);
+                    this.logger.info("constructServiceUrl......{}", userNumber);
+                    String url = "/portal";
+                    if (userNumber.contains("shr")) {
+                        url = "/shr";
+                    }
+
+                    response.sendRedirect("/eassso/privacyStatement/privacyStatementView.jsp?redirect=" + url);
+                } else {
+                    filterChain.doFilter(request, response);
+                }
+            } else {
+                serviceUrl = CommonUtils.constructServiceUrl(request, response, (String)null, this.getServerName(constructServerName), this.getProtocol().getServiceParameterName(), this.getProtocol().getArtifactParameterName(), true);
+                userNumber = this.retrieveTicketFromRequest(request);
+                boolean wasGatewayed = this.gateway && this.gatewayStorage.hasGatewayedAlready(request, serviceUrl);
+                if (!CommonUtils.isNotBlank(userNumber) && !wasGatewayed) {
+                    this.logger.debug("no ticket and no assertion found");
+                    String modifiedServiceUrl;
+                    if (this.gateway) {
+                        this.logger.debug("setting gateway attribute in session");
+                        modifiedServiceUrl = this.gatewayStorage.storeGatewayInformation(request, serviceUrl);
+                    } else {
+                        modifiedServiceUrl = serviceUrl;
+                    }
+
+                    this.logger.debug("Constructed service url: {}", modifiedServiceUrl);
+                    urlToRedirectTo = CommonUtils.constructRedirectUrl(this.casServerLoginUrl, this.getProtocol().getServiceParameterName(), modifiedServiceUrl, this.renew, this.gateway, this.method);
+                    this.logger.debug("redirecting to \"{}\"", urlToRedirectTo);
+                    if (!flag) {
+                        urlToRedirectTo = ConfigAddressUtil.getProperty("authUrl") + "?client_id=" + ConfigAddressUtil.getProperty("client_id") + "&response_type=code&redirect_uri=" + ConfigAddressUtil.getProperty("url") + "&response_mode=query&scope=openid%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&state=12345";
+                        this.logger.info("Request is RequestURL..........{}", request.getRequestURL());
+                        this.logger.info("Request is QueryString..........{}", request.getQueryString());
+                        session.setAttribute("isAdauth", "true");
+                        queryString = request.getQueryString();
+                        requestURL = String.valueOf(request.getRequestURL());
+                        if (!StringUtils.isEmpty(queryString) && !StringUtils.isEmpty(requestURL)) {
+                            Map<String, String> param = new HashMap();
+                            param.put("urlTo", requestURL + "?" + queryString);
+                            this.logger.info("Request is urlTo..........{}", requestURL + "?" + queryString);
+                            session.setAttribute("urlToMap", param);
+                        }
+                    }
+
+                    this.logger.info("doFilter.........urlToRedirectTo{}:", urlToRedirectTo);
+                    this.authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
+                } else {
+                    filterChain.doFilter(request, response);
+                }
+            }
+        }
+    }
+
+    protected String retrieveTicketFromRequest(HttpServletRequest request) {
+        String code = request.getParameter("code");
+        return !StringUtil.isEmpty(code) ? code : super.retrieveTicketFromRequest(request);
+    }
+
+    private boolean checkIsNeedPirvacyStatement(HttpServletRequest request) {
+        Context easContext = WebContextUtil.getEasContext(request);
+        if (easContext == null) {
+            return false;
+        } else if (easContext.get("privacyStatementKey") != null) {
+            return false;
+        } else {
+            String userId = easContext.getCaller().toString();
+            if (!"00000000-0000-0000-0000-00000000000013B7DE7F".equalsIgnoreCase(userId) && !"00000000-0000-0000-0000-00000000000213B7DE7F".equalsIgnoreCase(userId) && !"Wp3rRSFxRCaPFjuE2apQjRO33n8=".equalsIgnoreCase(userId) && !"00000000-0000-0000-0000-00000000000113B7DE7F".equalsIgnoreCase(userId) && !"256c221a-0106-1000-e000-10d7c0a813f413B7DE7F".equalsIgnoreCase(userId)) {
+                int privacyStatement = QrCodeTokenHelper.getPrivacyStatement();
+                if (privacyStatement == 0) {
+                    easContext.put("privacyStatementKey", 4);
+                    return false;
+                } else {
+                    int count = 0;
+                    String htmlContent = "";
+
+                    try {
+                        if (privacyStatement == 1) {
+                            String versionTime = "YS20220901";
+                            EntityViewInfo entityViewInfo = new EntityViewInfo();
+                            FilterInfo filterInfo = new FilterInfo();
+                            filterInfo.getFilterItems().add(new FilterItemInfo("userid", userId, CompareType.EQUALS));
+                            filterInfo.getFilterItems().add(new FilterItemInfo("versionTime", versionTime, CompareType.EQUALS));
+                            entityViewInfo.setFilter(filterInfo);
+                            count = PrivacyStatementFactory.getLocalInstance(easContext).getPrivacyStatementCollection(entityViewInfo).size();
+                        } else {
+                            EntityViewInfo entityViewInfo = new EntityViewInfo();
+                            FilterInfo filterInfo = new FilterInfo();
+                            filterInfo.getFilterItems().add(new FilterItemInfo("status", "ENABLE", CompareType.EQUALS));
+                            entityViewInfo.setFilter(filterInfo);
+                            PrivacyStatementCustomCollection customInfos = PrivacyStatementCustomFactory.getLocalInstance(easContext).getPrivacyStatementCustomCollection(entityViewInfo);
+                            if (customInfos.size() != 0) {
+                                PrivacyStatementCustomInfo privacyStatementCustomInfo = customInfos.get(0);
+                                filterInfo = new FilterInfo();
+                                filterInfo.getFilterItems().add(new FilterItemInfo("privacyCusId", privacyStatementCustomInfo.getId().toString(), CompareType.EQUALS));
+                                entityViewInfo = new EntityViewInfo();
+                                entityViewInfo.setFilter(filterInfo);
+                                count = PrivacyStatementFactory.getLocalInstance(easContext).getPrivacyStatementCollection(entityViewInfo).size();
+                                System.out.println("--- privacy state doExecute --count:" + count);
+                                htmlContent = privacyStatementCustomInfo.getHtmlContent();
+                            }
+                        }
+
+                        if (count > 0) {
+                            easContext.put("privacyStatementKey", 1);
+                            return false;
+                        }
+                    } catch (BOSException var11) {
+                        var11.printStackTrace();
+                        easContext.put("privacyStatementKey", 2);
+                        return false;
+                    }
+
+                    request.setAttribute("htmlContent", htmlContent);
+                    return true;
+                }
+            } else {
+                easContext.put("privacyStatementKey", 3);
+                return false;
+            }
+        }
+    }
+
+    private String getServerName(String constructServerName) {
+        if (constructServerName != null) {
+            return constructServerName;
+        } else {
+            try {
+                Class<?> clazz = this.getClass().getSuperclass();
+                Field field = clazz.getDeclaredField("serverName");
+                field.setAccessible(true);
+                return (String)field.get(this);
+            } catch (Exception var4) {
+                return null;
+            }
+        }
+    }
+
+    private String constructServerName(ServletRequest request) {
+        if (this.getServerNameFromRequest) {
+            StringBuilder serverName = new StringBuilder();
+            serverName.append(request.getServerName());
+            serverName.append(":");
+            serverName.append(request.getServerPort());
+            this.setServerName(serverName.toString());
+            return serverName.toString();
+        } else {
+            return null;
+        }
+    }
+
+    private void constructLoginUrl(ServletRequest request, boolean sessionRenew) {
+        HttpServletRequest httpRequest = (HttpServletRequest)request;
+        HttpSession session = httpRequest.getSession(false);
+        Assertion assertion = session != null ? (Assertion)session.getAttribute("_const_cas_assertion_") : null;
+
+        try {
+            URL contextURL = new URL(this.serverLoginUrl);
+            URL destURL = contextURL;
+            if (this.getServerLoginUrlFromRequest) {
+                destURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), contextURL.getFile());
+            }
+
+            if (assertion != null) {
+                this.setCasServerLoginUrl(destURL.toString());
+            } else {
+                String dataCenter = request.getParameter("dataCenter");
+                String dbType = request.getParameter("dbType");
+                String locale = request.getParameter("locale");
+                String renew = request.getParameter("renew");
+                if (sessionRenew) {
+                    renew = "true";
+                }
+
+                String optionParam = "";
+                if (dataCenter != null && !"".equals(dataCenter.trim())) {
+                    optionParam = optionParam + (optionParam.startsWith("?") ? "&dataCenter=" : "?dataCenter=") + dataCenter;
+                }
+
+                if (dbType != null && !"".equals(dbType.trim())) {
+                    optionParam = optionParam + (optionParam.startsWith("?") ? "&dbType=" : "?dbType=") + dbType;
+                }
+
+                if (locale != null && !"".equals(locale.trim())) {
+                    optionParam = optionParam + (optionParam.startsWith("?") ? "&locale=" : "?locale=") + locale;
+                }
+
+                if (renew != null && !"".equals(renew.trim())) {
+                    optionParam = optionParam + (optionParam.startsWith("?") ? "&renew=" : "?renew=") + renew;
+                }
+
+                this.setCasServerLoginUrl(destURL.toString() + optionParam);
+            }
+        } catch (MalformedURLException var13) {
+            var13.printStackTrace();
+        }
+
+    }
+
+    public final void setRenew(boolean renew) {
+        this.renew = renew;
+    }
+
+    public final void setGateway(boolean gateway) {
+        this.gateway = gateway;
+    }
+
+    public void setMethod(String method) {
+        this.method = method;
+    }
+
+    public final void setCasServerUrlPrefix(String casServerUrlPrefix) {
+        this.setCasServerLoginUrl(CommonUtils.addTrailingSlash(casServerUrlPrefix) + "login");
+    }
+
+    public final void setCasServerLoginUrl(String casServerLoginUrl) {
+        this.casServerLoginUrl = casServerLoginUrl;
+    }
+
+    public final void setGatewayStorage(GatewayResolver gatewayStorage) {
+        this.gatewayStorage = gatewayStorage;
+    }
+
+    private boolean isRequestUrlExcluded(HttpServletRequest request) throws MalformedURLException {
+        return FilterUtil.isUnFilter(request);
+    }
+
+    public final void setIgnoreUrlPatternMatcherStrategyClass(UrlPatternMatcherStrategy ignoreUrlPatternMatcherStrategyClass) {
+    }
+
+    public final void setServerLoginUrl(String serverLoginUrl) {
+        this.serverLoginUrl = serverLoginUrl;
+        this.setCasServerLoginUrl(this.serverLoginUrl);
+    }
+
+    public final void setGetServerNameFromRequest(boolean getServerNameFromRequest) {
+        this.getServerNameFromRequest = getServerNameFromRequest;
+    }
+
+    public final void setGetServerLoginUrlFromRequest(boolean getServerLoginUrlFromRequest) {
+        this.getServerLoginUrlFromRequest = getServerLoginUrlFromRequest;
+    }
+
+    private int getDeviceType(String requestHeader) {
+        if (requestHeader.indexOf("Android") != -1) {
+            return 1;
+        } else {
+            return requestHeader.indexOf("iPhone") == -1 && requestHeader.indexOf("iPad") == -1 ? 3 : 2;
+        }
+    }
+}

+ 262 - 0
GDYSL/src/com/kingdee/bos/sso/client/filter/validation/KDPortalTicketValidationFilter.java

@@ -0,0 +1,262 @@
+package com.kingdee.bos.sso.client.filter.validation;
+
+import com.kingdee.bos.Context;
+import com.kingdee.bos.sso.client.util.ConfigAddressUtil;
+import com.kingdee.bos.sso.client.util.FilterUtil;
+import com.kingdee.bos.sso.client.util.StringUtil;
+import com.kingdee.eas.cp.eip.sso.util.CloudParamUtil;
+import com.kingdee.eas.util.app.DbUtil;
+import com.kingdee.jdbc.rowset.IRowSet;
+import com.kingdee.util.StringUtils;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.ServletRequest;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import org.jasig.cas.client.authentication.AttributePrincipal;
+import org.jasig.cas.client.proxy.Cas20ProxyRetriever;
+import org.jasig.cas.client.proxy.ProxyGrantingTicketStorage;
+import org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl;
+import org.jasig.cas.client.ssl.HttpURLConnectionFactory;
+import org.jasig.cas.client.util.CommonUtils;
+import org.jasig.cas.client.validation.Assertion;
+import org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter;
+import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
+import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
+import org.jasig.cas.client.validation.TicketValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KDPortalTicketValidationFilter extends Cas20ProxyReceivingTicketValidationFilter {
+    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
+    private boolean getServerNameFromRequest;
+    private boolean getServerLoginUrlFromRequest;
+    private String casServerUrlPrefix;
+    private String acceptAnyProxy;
+    private String allowedProxyChains;
+    private String proxyCallbackUrl;
+    private boolean renew;
+    private String encoding;
+    private Map<String, String> additionalParameters = new HashMap();
+    private ProxyGrantingTicketStorage proxyGrantingTicketStorage = new ProxyGrantingTicketStorageImpl();
+
+    public KDPortalTicketValidationFilter() {
+    }
+
+    protected String retrieveTicketFromRequest(HttpServletRequest request) {
+        String servletPath = request.getServletPath();
+
+        try {
+            if (FilterUtil.isUnFilter(request)) {
+                return null;
+            }
+
+            this.constructLoginUrl(request);
+            this.constructServerName(request);
+            if (!"/webviews/workflow/viewProcessDiagram.jsp".equals(servletPath) && !"/dynamicPage.do".equals(servletPath) && !"/common/tree.do".equals(servletPath)) {
+                this.setTicketValidator(this.getTicketValidatorToSso(request));
+            } else {
+                this.setTicketValidator(this.getTicketValidator());
+            }
+        } catch (MalformedURLException var4) {
+            var4.printStackTrace();
+        }
+
+        String code = request.getParameter("code");
+        return !StringUtil.isEmpty(code) && !"/webviews/workflow/viewProcessDiagram.jsp".equals(servletPath) && !"/dynamicPage.do".equals(servletPath) && !"/common/tree.do".equals(servletPath) ? code : super.retrieveTicketFromRequest(request);
+    }
+
+    protected TicketValidator getTicketValidator() {
+        Cas20ServiceTicketValidator validator = null;
+        if (!CommonUtils.isNotBlank(this.acceptAnyProxy) && !CommonUtils.isNotBlank(this.allowedProxyChains)) {
+            validator = new Cas20ServiceTicketValidator(this.casServerUrlPrefix);
+        } else {
+            Cas20ProxyTicketValidator v = new Cas20ProxyTicketValidator(this.casServerUrlPrefix);
+            v.setAcceptAnyProxy("true".equalsIgnoreCase(this.acceptAnyProxy));
+            v.setAllowedProxyChains(CommonUtils.createProxyList(this.allowedProxyChains));
+        }
+
+        validator.setProxyCallbackUrl(this.proxyCallbackUrl);
+        validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage);
+        validator.setProxyRetriever(new Cas20ProxyRetriever(this.casServerUrlPrefix, this.encoding));
+        validator.setRenew(this.renew);
+        validator.setEncoding(this.encoding);
+        validator.setURLConnectionFactory(new KDPortalTicketConnectionFactory());
+        validator.setCustomParameters(this.additionalParameters);
+        return validator;
+    }
+
+    protected TicketValidator getTicketValidatorToSso(HttpServletRequest request) {
+        String code = request.getParameter("code");
+        String servletPath = request.getServletPath();
+        this.logger.info("KDPortalTicketValidationFilter......getTicketValidator...servletPath{} ", servletPath);
+        if (!StringUtil.isEmpty(code) && !"/webviews/workflow/viewProcessDiagram.jsp".equals(servletPath)) {
+            return new OAuth20CodeValidata();
+        } else {
+            Cas20ServiceTicketValidator validator = null;
+            if (!CommonUtils.isNotBlank(this.acceptAnyProxy) && !CommonUtils.isNotBlank(this.allowedProxyChains)) {
+                validator = new Cas20ServiceTicketValidator(this.casServerUrlPrefix);
+            } else {
+                Cas20ProxyTicketValidator v = new Cas20ProxyTicketValidator(this.casServerUrlPrefix);
+                v.setAcceptAnyProxy("true".equalsIgnoreCase(this.acceptAnyProxy));
+                v.setAllowedProxyChains(CommonUtils.createProxyList(this.allowedProxyChains));
+            }
+
+            validator.setProxyCallbackUrl(this.proxyCallbackUrl);
+            validator.setProxyGrantingTicketStorage(this.proxyGrantingTicketStorage);
+            validator.setProxyRetriever(new Cas20ProxyRetriever(this.casServerUrlPrefix, this.encoding));
+            validator.setRenew(this.renew);
+            validator.setEncoding(this.encoding);
+            validator.setURLConnectionFactory(new KDPortalTicketConnectionFactory());
+            validator.setCustomParameters(this.additionalParameters);
+            return validator;
+        }
+    }
+
+    protected void onSuccessfulValidation(HttpServletRequest request, HttpServletResponse response, Assertion assertion) {
+        try {
+            this.logger.info("onSuccessfulValidation......assertion{}", assertion);
+            AttributePrincipal principal = assertion.getPrincipal();
+            this.logger.info("onSuccessfulValidation......principal{}", principal);
+            if (principal == null) {
+                return;
+            }
+
+            String isIndependentDeployment = System.getProperty("cas.server.IsIndependentDeployment") == null ? "" : System.getProperty("cas.server.IsIndependentDeployment");
+            String dataCenter = "";
+            String locale = "";
+            this.logger.info("onSuccessfulValidation......isIndependentDeployment:{}", isIndependentDeployment);
+            dataCenter = ConfigAddressUtil.getProperty("dataCenter");
+            locale = ConfigAddressUtil.getProperty("locale");
+            this.logger.info("onSuccessfulValidation......dataCenter:{}", dataCenter);
+            this.logger.info("onSuccessfulValidation......locale:{}", locale);
+            String username = principal.getName();
+            this.logger.info("onSuccessfulValidation......username{}", username);
+            if (StringUtils.isEmpty(dataCenter) || StringUtils.isEmpty(locale) || StringUtils.isEmpty(username)) {
+                return;
+            }
+
+            Context ctx = CloudParamUtil.getContext(dataCenter, locale, "administrator");
+            String sql = "SELECT count(1) FROM T_PM_USER WHERE LOWER(FNUMBER)=?";
+            IRowSet rs = DbUtil.executeQuery(ctx, sql, new Object[]{username.toLowerCase()});
+            if (rs.next()) {
+                int count = Integer.valueOf(rs.getString(1));
+                if (count < 1) {
+                    this.logger.info("onSuccessfulValidation......notfounduser", username);
+                    response.sendRedirect("/eassso/unreg/unvalibaleUser.jsp?username=" + username);
+                }
+            }
+
+            HttpSession session = request.getSession();
+            if (session != null) {
+                String requestHeader = request.getHeader("user-agent");
+                this.logger.info("onSuccessfulValidation......跳转doFilter..........requestHeader{} ", requestHeader);
+                this.logger.info("request.getRequestURL():" + request.getRequestURL());
+                int type = this.getDeviceType(requestHeader);
+                String urlTo;
+                if (type == 1 || type == 2) {
+                    this.logger.info("跳转移动端.getDeviceType.type:" + type);
+                    String requestUrl = request.getRequestURL().toString();
+                    urlTo = ConfigAddressUtil.getProperty("mobileEid");
+                    this.logger.info("onSuccessfulValidation.eid:" + urlTo);
+                    this.logger.info("判断是否为移动端_onSuccessfulValidation.username:" + username);
+                    session.setAttribute("userNumber", username);
+                    String url = requestUrl + "index2.do?eid=" + urlTo + "&appid=10036&param=" + username;
+                    this.logger.info("onSuccessfulValidation......跳转移动端的URL:{}", url);
+                    response.sendRedirect(url);
+                    return;
+                }
+
+                Map<String, String> urlToMap = (Map)session.getAttribute("urlToMap");
+                if (urlToMap != null && urlToMap.size() > 0) {
+                    urlTo = (String)urlToMap.get("urlTo");
+                    this.logger.info("onSuccessfulValidation......urlTo{}...", urlTo);
+                    if (!StringUtils.isEmpty(urlTo)) {
+                        response.sendRedirect(urlTo);
+                        session.removeAttribute("urlToMap");
+                    }
+                }
+            }
+        } catch (Exception var18) {
+            var18.printStackTrace();
+        }
+
+    }
+
+    private int getDeviceType(String requestHeader) {
+        if (requestHeader.indexOf("Android") != -1) {
+            return 1;
+        } else {
+            return requestHeader.indexOf("iPhone") == -1 && requestHeader.indexOf("iPad") == -1 ? 3 : 2;
+        }
+    }
+
+    private void constructLoginUrl(ServletRequest request) {
+        if (this.getServerLoginUrlFromRequest) {
+            try {
+                URL contextURL = new URL(this.casServerUrlPrefix);
+                URL destURL = new URL(contextURL.getProtocol(), request.getServerName(), request.getServerPort(), contextURL.getFile());
+                this.casServerUrlPrefix = destURL.toString();
+            } catch (MalformedURLException var4) {
+                var4.printStackTrace();
+            }
+        }
+
+    }
+
+    private void constructServerName(ServletRequest request) {
+        if (this.getServerNameFromRequest) {
+            StringBuilder serverName = new StringBuilder();
+            serverName.append(request.getServerName());
+            serverName.append(":");
+            serverName.append(request.getServerPort());
+            this.setServerName(serverName.toString());
+        }
+
+    }
+
+    public final void setGetServerNameFromRequest(boolean getServerNameFromRequest) {
+        this.getServerNameFromRequest = getServerNameFromRequest;
+    }
+
+    public final void setGetServerLoginUrlFromRequest(boolean getServerLoginUrlFromRequest) {
+        this.getServerLoginUrlFromRequest = getServerLoginUrlFromRequest;
+    }
+
+    public final void setCasServerUrlPrefix(String casServerUrlPrefix) {
+        this.casServerUrlPrefix = casServerUrlPrefix;
+    }
+
+    public final void setAcceptAnyProxy(String acceptAnyProxy) {
+        this.acceptAnyProxy = acceptAnyProxy;
+    }
+
+    public final void setAllowedProxyChains(String allowedProxyChains) {
+        this.allowedProxyChains = allowedProxyChains;
+    }
+
+    public final void setProxyCallbackUrl(String proxyCallbackUrl) {
+        this.proxyCallbackUrl = proxyCallbackUrl;
+    }
+
+    public final void setRenew(boolean renew) {
+        this.renew = renew;
+    }
+
+    public final void setEncoding(String encoding) {
+        this.encoding = encoding;
+    }
+
+    class KDPortalTicketConnectionFactory implements HttpURLConnectionFactory {
+
+
+        public HttpURLConnection buildHttpURLConnection(URLConnection connection) {
+            return (HttpURLConnection)connection;
+        }
+    }
+}

+ 162 - 0
GDYSL/src/com/kingdee/bos/sso/client/filter/validation/OAuth20CodeValidata.java

@@ -0,0 +1,162 @@
+package com.kingdee.bos.sso.client.filter.validation;
+
+import com.alibaba.fastjson.JSON;
+import com.kingdee.bos.metadata.entity.EntityViewInfo;
+import com.kingdee.bos.metadata.entity.FilterInfo;
+import com.kingdee.bos.metadata.entity.FilterItemInfo;
+import com.kingdee.bos.metadata.entity.SelectorItemCollection;
+import com.kingdee.bos.metadata.entity.SelectorItemInfo;
+import com.kingdee.bos.sso.client.util.ConfigAddressUtil;
+import com.kingdee.bos.sso.client.util.HttpClientUtil;
+import com.kingdee.eas.base.permission.UserCollection;
+import com.kingdee.eas.base.permission.UserFactory;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import oadd.org.apache.commons.lang.StringUtils;
+import org.jasig.cas.client.authentication.AttributePrincipalImpl;
+import org.jasig.cas.client.validation.Assertion;
+import org.jasig.cas.client.validation.AssertionImpl;
+import org.jasig.cas.client.validation.TicketValidationException;
+import org.jasig.cas.client.validation.TicketValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class OAuth20CodeValidata implements TicketValidator {
+    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
+
+
+
+    public Assertion validate(String code, String url) throws TicketValidationException {
+        String redirect_uri = ConfigAddressUtil.getProperty("url");
+        this.logger.info("validate....code:{}", code);
+        this.logger.info("validate....url:{}", url);
+        this.logger.info("validate....redirect_uri:{}", url);
+        String token = this.getToken(code, ConfigAddressUtil.getProperty("tokenUrl"), redirect_uri);
+        this.logger.info("validate....token:" + token);
+        String userEntity = this.getUser(token, ConfigAddressUtil.getProperty("userUrl"));
+        String user = "";
+        if (StringUtils.isNotBlank(userEntity)) {
+            String[] split = userEntity.split("@");
+            user = split[0];
+            this.logger.info("validate....user..split[0]:{}", user);
+        }
+
+        Map<String, Object> map = new HashMap();
+        map.put("solutionName", "eas");
+        map.put("dataCenter", ConfigAddressUtil.getProperty("dataCenter"));
+        map.put("locale", ConfigAddressUtil.getProperty("locale"));
+        map.put("dbType", "0");
+        map.put("userAuthPattern", "aseAD");
+        map.put("isPureWeb", "true");
+        map.put("loginFlow", "true");
+        map.put("sso.user.mapping", "true");
+        Assertion assertion = new AssertionImpl(new AttributePrincipalImpl(user, map));
+        return assertion;
+    }
+
+    private String getToken(String code, String url, String redirect_uri) {
+        String result = "";
+
+        try {
+            Map<String, Object> map = new HashMap();
+            map.put("grant_type", "authorization_code");
+            map.put("client_id", ConfigAddressUtil.getProperty("client_id"));
+            map.put("client_secret", ConfigAddressUtil.getProperty("client_secret"));
+            map.put("code", code);
+            map.put("redirect_uri", URLEncoder.encode(redirect_uri, "utf-8"));
+            this.logger.info("get_token....RequestParam{}", JSON.toJSONString(map));
+            result = HttpClientUtil.sendPostRequest(url, map);
+            this.logger.info("get_token.... respone{}", result);
+        } catch (Exception var7) {
+            this.logger.info("get_token....throw", var7);
+        }
+
+        Map<String, String> resultMap = (Map)JSON.parseObject(result, Map.class);
+        String token = "";
+        if (resultMap != null) {
+            token = (String)resultMap.get("access_token");
+        }
+
+        return token;
+    }
+
+    private String getUser(String token, String url) {
+        String result = "";
+
+        try {
+            result = HttpClientUtil.HttpGet(url, token);
+        } catch (Exception var6) {
+            this.logger.info("getUser....throw{}", var6.getMessage());
+        }
+
+        this.logger.info("getUser...." + result);
+        Map<String, String> resultMap = (Map)JSON.parseObject(result, Map.class);
+        String user = "";
+        if (resultMap != null) {
+            user = (String)resultMap.get("userPrincipalName");
+        }
+
+        return user;
+    }
+
+    private Boolean queryShrUser(String userNum) {
+        UserCollection userCollection = null;
+        Map<String, Object> map = new HashMap();
+        map.put("number", userNum);
+        EntityViewInfo entityViewInfo = this.getEntityViewInfo(map);
+
+        try {
+            userCollection = UserFactory.getRemoteInstance().getUserCollection(entityViewInfo);
+        } catch (Exception var6) {
+            this.logger.info("queryShrUser....{}", var6);
+        }
+
+        return userCollection != null && userCollection.size() > 0;
+    }
+
+    private EntityViewInfo getEntityViewInfo(Map<String, Object> map) {
+        EntityViewInfo entityViewInfo = new EntityViewInfo();
+        SelectorItemCollection sic = new SelectorItemCollection();
+        sic.add(new SelectorItemInfo("*"));
+        FilterInfo filters = new FilterInfo();
+        if (map != null) {
+            Iterator<Map.Entry<String, Object>> entrys = map.entrySet().iterator();
+
+            while(entrys.hasNext()) {
+                Map.Entry<String, Object> entry = (Map.Entry)entrys.next();
+                filters.getFilterItems().add(new FilterItemInfo((String)entry.getKey(), entry.getValue()));
+            }
+
+            entityViewInfo.setFilter(filters);
+            entityViewInfo.setSelector(sic);
+        }
+
+        return entityViewInfo;
+    }
+
+    private String refreshToken(String url, String token, String redirect_uri) {
+        String result = "";
+
+        try {
+            Map<String, Object> map = new HashMap();
+            map.put("grant_type", "refresh_token");
+            map.put("client_id", "f39393eb-3669-4257-829a-8dae118d6691");
+            map.put("client_secret", "zvM8Q~9mj2KTbp5gLyl4ZuuPWH7-HhsIqb68ectN");
+            map.put("refresh_token", token);
+            map.put("redirect_uri", URLEncoder.encode(redirect_uri, "utf-8"));
+            result = HttpClientUtil.sendPostRequest(url, map);
+        } catch (Exception var7) {
+            this.logger.info("refreshToken....throw{}", var7);
+        }
+
+        Map<String, String> resultMap = (Map)JSON.parseObject(result, Map.class);
+        String refreToken = "";
+        if (resultMap != null) {
+            refreToken = (String)resultMap.get("access_token");
+        }
+
+        return refreToken;
+    }
+}