Browse Source

opem

master
pioneer 2 years ago
commit
d09b1bde68
  1. 6
      README.md
  2. BIN
      doc/JSD-9765配置使用文档.docx
  3. 19
      plugin.xml
  4. 9
      src/main/java/com/fr/plugin/xx/saml/Constants.java
  5. 16
      src/main/java/com/fr/plugin/xx/saml/CustomLogInOutEventProvider.java
  6. 65
      src/main/java/com/fr/plugin/xx/saml/DesECBUtil.java
  7. 113
      src/main/java/com/fr/plugin/xx/saml/KeysUtil.java
  8. 28
      src/main/java/com/fr/plugin/xx/saml/LRGT.java
  9. 227
      src/main/java/com/fr/plugin/xx/saml/LoginFilter.java
  10. 95
      src/main/java/com/fr/plugin/xx/saml/conf/SamlSsoConfig.java
  11. 121
      src/main/java/com/fr/plugin/xx/saml/util/LogUtils.java

6
README.md

@ -0,0 +1,6 @@
# open-JSD-9765
JSD-9765 与客户系统做单点集成\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。

BIN
doc/JSD-9765配置使用文档.docx

Binary file not shown.

19
plugin.xml

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.fr.plugin.xx.saml</id>
<name><![CDATA[saml单点]]></name>
<active>yes</active>
<version>1.0</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[saml单点]]></description>
<change-notes><![CDATA[
[2022-04-27]【1.0】初始化插件<br/>
]]></change-notes>
<lifecycle-monitor class="com.fr.plugin.xx.xx.saml.LRGT"/>
<extra-decision>
<LogInOutEventProvider class="com.fr.plugin.xx.saml.CustomLogInOutEventProvider"/>
<GlobalRequestFilterProvider class="com.fr.plugin.xx.saml.LoginFilter"/>
</extra-decision>
<function-recorder class="com.fr.plugin.xx.saml.LoginFilter"/>
</plugin>

9
src/main/java/com/fr/plugin/xx/saml/Constants.java

@ -0,0 +1,9 @@
package com.fr.plugin.xx.saml;
/**
* @author xx
* @date 2020/11/11
*/
public class Constants {
public static final String PLUGIN_ID = "com.fr.plugin.xx.saml";
}

16
src/main/java/com/fr/plugin/xx/saml/CustomLogInOutEventProvider.java

@ -0,0 +1,16 @@
package com.fr.plugin.xx.saml;
import com.fr.decision.fun.impl.AbstractLogInOutEventProvider;
import com.fr.decision.webservice.login.LogInOutResultInfo;
import com.fr.plugin.xx.saml.conf.SamlSsoConfig;
/**
* @author xx
* @date 2020/11/11
*/
public class CustomLogInOutEventProvider extends AbstractLogInOutEventProvider {
@Override
public String logoutAction(LogInOutResultInfo result) {
return SamlSsoConfig.getInstance().getLogout();
}
}

65
src/main/java/com/fr/plugin/xx/saml/DesECBUtil.java

@ -0,0 +1,65 @@
package com.fr.plugin.xx.saml;
import com.fr.third.org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
/**
* @author xx
* @date 2020/11/11
*/
public class DesECBUtil {
/**
* 加密数据
*
* @param encryptString
* @param encryptKey
* @return
* @throws Exception
*/
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(getKey(encryptKey), "DES"));
byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
return Base64.encodeBase64String(encryptedData);
}
/**
* key 不足8位补位
*
* @param
*/
public static byte[] getKey(String keyRule) {
Key key = null;
byte[] keyByte = keyRule.getBytes();
// 创建一个空的八位数组,默认情况下为0
byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
key = new SecretKeySpec(byteTemp, "DES");
return key.getEncoded();
}
/***
* 解密数据
* @param decryptString
* @param decryptKey
* @return
* @throws Exception
*/
public static String decryptDES(String decryptString, String decryptKey) throws Exception {
byte[] sourceBytes = Base64.decodeBase64(decryptString);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(getKey(decryptKey), "DES"));
byte[] decoded = cipher.doFinal(sourceBytes);
return new String(decoded, "UTF-8");
}
}

113
src/main/java/com/fr/plugin/xx/saml/KeysUtil.java

@ -0,0 +1,113 @@
package com.fr.plugin.xx.saml;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
/**
* @author xx
* @date 2020/11/11
*/
public class KeysUtil {
private final static String ALGORITHM = "DES";
/**
* 加密
* @param data 未加密数据
* @param key 加密key
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] dataBytes = data.getBytes("UTF-8");
byte[] keyBytes = key.getBytes("UTF-8");
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(keyBytes);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// 正式执行加密操作
byte[] bytes = cipher.doFinal(dataBytes);
return byte2hex(bytes);
}
/**
* 解密
* @param data 加密后的数据
* @param key 加密key
* @return
* @throws Exception
*/
public static String decrypt(String data, String key) throws Exception {
byte[] dataBytes = data.getBytes("UTF-8");
byte[] hex2byte = hex2byte(dataBytes);
byte[] keyBytes = key.getBytes("UTF-8");
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密匙数据创建一个DESKeySpec对象
DESKeySpec dks = new DESKeySpec(keyBytes);
// 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
// 一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
// 正式执行解密操作
byte[] doFinal = cipher.doFinal(hex2byte);
return new String(doFinal,"UTF-8");
}
private static byte[] hex2byte(byte[] b) throws UnsupportedEncodingException {
if ((b.length % 2) != 0) {
throw new IllegalArgumentException("长度不是偶数");
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2, "UTF-8");
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
private static String byte2hex(byte[] b) {
StringBuilder bulid = new StringBuilder();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
bulid.append("0").append(stmp);
} else {
bulid.append(stmp);
}
}
return bulid.toString().toUpperCase();
}
}

28
src/main/java/com/fr/plugin/xx/saml/LRGT.java

@ -0,0 +1,28 @@
package com.fr.plugin.xx.saml;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.xx.saml.conf.SamlSsoConfig;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
/**
* 配置信息初始化
*/
public class LRGT extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
SamlSsoConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
@Override
public void beforeUninstall(PluginContext pluginContext) {
}
@Override
public void afterInstall(PluginContext var1) {
}
}

227
src/main/java/com/fr/plugin/xx/saml/LoginFilter.java

@ -0,0 +1,227 @@
package com.fr.plugin.xx.saml;/*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this
* file except in compliance with the License. You may obtain
* a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
*
* The Original Code is OIOSAML Java Service Provider.
*
* The Initial Developer of the Original Code is Trifork A/S. Portions
* created by Trifork A/S are Copyright (C) 2008 Danish National IT
* and Telecom Agency (http://www.itst.dk). All Rights Reserved.
*
* Contributor(s):
* Joakim Recht <jre@trifork.com>
* Rolf Njor Jensen <rolf@trifork.com>
* Aage Nielsen <ani@openminds.dk>
*
*/
import com.fr.data.NetworkHelper;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.mobile.terminal.TerminalHandler;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.utils.WebServiceUtils;
import com.fr.decision.webservice.v10.config.ConfigService;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.login.TokenResource;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.intelli.record.Focus;
import com.fr.intelli.record.Original;
import com.fr.locale.InterProviderFactory;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.xx.saml.conf.SamlSsoConfig;
import com.fr.plugin.xx.saml.util.LogUtils;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.stable.StringUtils;
import com.fr.stable.fun.Authorize;
import com.fr.stable.web.Device;
import com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* @author xx
* @date 2020/11/11
*/
@FunctionRecorder
@Authorize(callSignKey = Constants.PLUGIN_ID)
@EnableMetrics
public class LoginFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "xx";
}
@Override
@Focus(id = Constants.PLUGIN_ID, text = "迈瑞smal", source = Original.PLUGIN)
public String[] urlPatterns() {
if (PluginContexts.currentContext().isAvailable()) {
String servletPathName = "decision";
try {
servletPathName = ConfigService.getInstance().getBasicParam().getServletPathName();
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
return new String[]{
"/" + servletPathName,
"/" + servletPathName + "/view/report",
"/" + servletPathName + "/view/form",
};
} else {
return new String[]{"/neverbeused"};
}
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
String samlToken = req.getParameter("samlToken");
SamlSsoConfig config = SamlSsoConfig.getInstance();
try {
if (isAccept(req) || isLogin(req)) {
next(req, res, filterChain);
return;
}
if (StringUtils.isNotBlank(samlToken)) {
if(!config.isAccept()){
setError(res, String.format("单点登录配置未完成"));
return;
}
String key = config.getKey();
LogUtils.debug4plugin("get key config is {}", key);
String format = DesECBUtil.decryptDES(samlToken, key);
LogUtils.debug4plugin("decode format is {}", format);
String user = format.split("_")[0];
String timeout = format.split("_")[1];
Integer out = config.getTimeout();
LogUtils.debug4plugin("get timeout config is {}", out);
if (Instant.ofEpochMilli(Long.valueOf(timeout)).plusSeconds((out)).isBefore(Instant.now())) {
setError(res, "format timeout!");
return;
}
if (!checkUser(user)) {
setError(res, "user: 【" + user + "】 not exist !");
return;
}
loginFromToken(req, res, user);
}
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
LogUtils.debug4plugin("current request {} not login send redirect login", getUrl(req));
String saml = config.getSamlUrl();
try {
res.sendRedirect(saml);
} catch (IOException e) {
LogUtils.error(e.getMessage(), e);
}
}
private String getUrl(HttpServletRequest req) {
String requestURL = req.getRequestURL().toString();
String queryString = req.getQueryString();
if (StringUtils.isNotBlank(queryString)) {
requestURL += "?" + queryString;
}
return requestURL;
}
private boolean isLogin(HttpServletRequest request) throws Exception {
String oldToken = TokenResource.COOKIE.getToken(request);
return oldToken != null && checkTokenValid(request, (String) oldToken);
}
private boolean checkTokenValid(HttpServletRequest req, String token) {
try {
Device device = NetworkHelper.getDevice(req);
LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, device));
return true;
} catch (Exception ignore) {
}
return false;
}
private boolean isAccept(HttpServletRequest req) {
if (req.getRequestURI().endsWith("/view/form") || req.getRequestURI().endsWith("/view/report")) {
return StringUtils.isBlank(WebUtils.getHTTPRequestParameter(req, "viewlet")) && StringUtils.isNotBlank(req.getParameter("samlToken"));
}
return false;
}
private void next(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
try {
chain.doFilter(request, response);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private boolean checkUser(String username) {
User user = null;
try {
user = UserService.getInstance().getUserByUserName(username);
LogUtils.debug4plugin("get user:" + user);
if (user != null) {
return true;
}
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
return false;
}
private boolean loginFromToken(HttpServletRequest req, HttpServletResponse res, String username) throws Exception {
try {
if (StringUtils.isNotEmpty(username)) {
LogUtils.debug4plugin("current username:" + username);
String token = LoginService.getInstance().login(req, res, username);
LogUtils.debug4plugin("get login token:" + token);
req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
LogUtils.debug4plugin("username:" + username + "login success");
return true;
} else {
LogUtils.warn("username is null!");
return false;
}
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
return false;
}
private void setError(HttpServletResponse res, String reason) {
try {
PrintWriter printWriter = WebUtils.createPrintWriter(res);
Map<String, Object> map = new HashMap<>();
map.put("result", InterProviderFactory.getProvider().getLocText("Fine-Engine_Error_Page_Result"));
map.put("reason", reason);
map.put("solution", InterProviderFactory.getProvider().getLocText("Fine-Engine_Please_Contact_Platform_Admin"));
String page = WebServiceUtils.parseWebPageResourceSafe("com/fr/web/controller/decision/entrance/resources/unavailable.html", map);
printWriter.write(page);
printWriter.flush();
printWriter.close();
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
}
}

95
src/main/java/com/fr/plugin/xx/saml/conf/SamlSsoConfig.java

@ -0,0 +1,95 @@
package com.fr.plugin.xx.saml.conf;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
import com.fr.stable.StringUtils;
/**
* @author xx
* @since 2021/12/04
*/
@Visualization(category = "saml门户配置")
public class SamlSsoConfig extends DefaultConfiguration {
private static volatile SamlSsoConfig config = null;
public static SamlSsoConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(SamlSsoConfig.class);
}
return config;
}
@Identifier(value = "debugSwitch", name = "插件调试开关", description = "日志调试模式", status = Status.SHOW)
private Conf<Boolean> debugSwitch = Holders.simple(true);
public Boolean getDebugSwitch() {
return debugSwitch.get();
}
public void setDebugSwitch(Boolean debugSwitch) {
this.debugSwitch.set(debugSwitch);
}
@Identifier(value = "key", name = "解密秘钥", description = "解密秘钥", status = Status.SHOW)
private Conf<String> key = Holders.simple(StringUtils.EMPTY);
public String getKey() {
return key.get();
}
public void setKey(String k) {
key.set(k);
}
@Identifier(value = "timeout", name = "超时时间", description = "超时时间", status = Status.SHOW)
private Conf<Integer> timeout = Holders.simple(10);
public Integer getTimeout() {
return timeout.get();
}
public void setTimeout(Integer time) {
timeout.set(time);
}
@Identifier(value = "samlUrl", name = "saml跳转地址", description = "saml跳转地址", status = Status.SHOW)
private Conf<String> samlUrl = Holders.simple(StringUtils.EMPTY);
public String getSamlUrl() {
return samlUrl.get();
}
public void setSamlUrl(String key) {
samlUrl.set(key);
}
@Identifier(value = "logout", name = "logout", description = "登出地址", status = Status.SHOW)
private Conf<String> logout = Holders.simple(StringUtils.EMPTY);
public String getLogout() {
return logout.get();
}
public void setLogout(String key) {
logout.set(key);
}
@Override
public Object clone() throws CloneNotSupportedException {
SamlSsoConfig cloned = (SamlSsoConfig) super.clone();
cloned.debugSwitch = (Conf<Boolean>) debugSwitch.clone();
cloned.logout = (Conf<String>) logout.clone();
cloned.timeout = (Conf<Integer>) timeout.clone();
cloned.key = (Conf<String>) key.clone();
cloned.samlUrl = (Conf<String>) samlUrl.clone();
return cloned;
}
public boolean isAccept() {
return StringUtils.isNotBlank(getKey()) && StringUtils.isNotBlank(getSamlUrl());
}
}

121
src/main/java/com/fr/plugin/xx/saml/util/LogUtils.java

@ -0,0 +1,121 @@
package com.fr.plugin.xx.saml.util;
import com.fr.log.FineLoggerFactory;
import com.fr.log.FineLoggerProvider;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.xx.saml.conf.SamlSsoConfig;
import com.fr.stable.StringUtils;
/**
* @author xx
* @since 2021/12/04
*/
public final class LogUtils {
private static final String DEBUG_PREFIX = "[插件调试] ";
private static String LOG_PREFIX = "[SMAL单点] ";
private static final String PLUGIN_VERSION;
private static final FineLoggerProvider LOGGER = FineLoggerFactory.getLogger();
static {
String version = PluginContexts.currentContext().getMarker().getVersion();
if (StringUtils.isNotBlank(version)) {
PLUGIN_VERSION = "[v" + version + "] ";
} else {
PLUGIN_VERSION = "[unknown version] ";
}
LOG_PREFIX = LOG_PREFIX + PLUGIN_VERSION;
}
public static void setPrefix(String prefix) {
if (prefix != null) {
LOG_PREFIX = prefix;
}
}
public static boolean isDebugEnabled() {
return LOGGER.isDebugEnabled();
}
public static void debug(String s) {
LOGGER.debug(LOG_PREFIX + s);
}
public static void debug(String s, Object... objects) {
LOGGER.debug(LOG_PREFIX + s, objects);
}
public static void debug(String s, Throwable throwable) {
LOGGER.debug(LOG_PREFIX + s, throwable);
}
public static void debug4plugin(String s) {
if (SamlSsoConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s);
} else {
LOGGER.debug(LOG_PREFIX + s);
}
}
public static void debug4plugin(String s, Object... objects) {
if (SamlSsoConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, objects);
} else {
LOGGER.debug(LOG_PREFIX + s, objects);
}
}
public static void debug4plugin(String s, Throwable throwable) {
if (SamlSsoConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, throwable);
} else {
LOGGER.debug(LOG_PREFIX + s, throwable);
}
}
public static boolean isInfoEnabled() {
return LOGGER.isInfoEnabled();
}
public static void info(String s) {
LOGGER.info(LOG_PREFIX + s);
}
public static void info(String s, Object... objects) {
LOGGER.info(LOG_PREFIX + s, objects);
}
public static void warn(String s) {
LOGGER.warn(LOG_PREFIX + s);
}
public static void warn(String s, Object... objects) {
LOGGER.warn(LOG_PREFIX + s, objects);
}
public static void warn(String s, Throwable throwable) {
LOGGER.warn(LOG_PREFIX + s, throwable);
}
public static void warn(Throwable throwable, String s, Object... objects) {
LOGGER.warn(throwable, LOG_PREFIX + s, objects);
}
public static void error(String s) {
LOGGER.error(LOG_PREFIX + s);
}
public static void error(String s, Object... objects) {
LOGGER.error(LOG_PREFIX + s, objects);
}
public static void error(String s, Throwable throwable) {
LOGGER.error(LOG_PREFIX + s, throwable);
}
public static void error(Throwable throwable, String s, Object... objects) {
LOGGER.error(throwable, LOG_PREFIX + s, objects);
}
}
Loading…
Cancel
Save