Browse Source

JSD-11225,JSD-11431 台州银行驾驶舱项目 单点登录及统一身份认证

master
liunianbo 2 years ago
commit
242c87c15b
  1. 4
      README.md
  2. 135
      build.gradle
  3. 13
      encrypt.xml
  4. BIN
      lib/DesSecurity.jar
  5. BIN
      lib/commons-beanutils-1.9.4.jar
  6. BIN
      lib/commons-collections-3.2.2.jar
  7. BIN
      lib/commons-lang-2.6.jar
  8. BIN
      lib/commons-logging-1.2.jar
  9. BIN
      lib/ezmorph-1.0.6.jar
  10. BIN
      lib/json-lib-2.4-jdk15.jar
  11. 25
      plugin.xml
  12. 22
      src/main/java/com/fr/plugin/decision/auth/LoginPluginLifecycle.java
  13. 61
      src/main/java/com/fr/plugin/decision/auth/RequestReaderHttpServletRequestWrapper.java
  14. 100
      src/main/java/com/fr/plugin/decision/auth/config/AuthLoginPluginConfig.java
  15. 100
      src/main/java/com/fr/plugin/decision/auth/config/SsoLoginPluginConfig.java
  16. 546
      src/main/java/com/fr/plugin/decision/auth/filter/AuthLoginRequestFilter.java
  17. 286
      src/main/java/com/fr/plugin/decision/auth/filter/SsoLoginRequestFilter.java
  18. 28
      src/main/java/com/fr/plugin/decision/auth/utils/FRUtils.java

4
README.md

@ -0,0 +1,4 @@
# open-JSD-11225
JSD-11225 统一身份认证

135
build.gradle

@ -0,0 +1,135 @@
apply plugin: 'java'
ext {
/**
* jar的路径
* 1.jar需要打包到zip中,lib根目录下
* 2.jar仅仅是编译时需要lib下子目录下即可
*/
libPath = "$projectDir/../webroot/WEB-INF/lib"
/**
* class进行加密保护
*/
guard = true
def pluginInfo = getPluginInfo()
pluginPre = "fine-plugin"
pluginName = pluginInfo.id
pluginVersion = pluginInfo.version
outputPath = "$projectDir/../webroot/WEB-INF/plugins/plugin-" + pluginName + "-1.0/classes"
}
group = 'com.fr.plugin'
version = '11.0'
sourceCompatibility = '8'
sourceSets {
main {
java.outputDir = file(outputPath)
output.resourcesDir = file(outputPath)
}
}
ant.importBuild("encrypt.xml")
//ant变量
ant.projectDir = projectDir
ant.references["compile.classpath"] = ant.path {
fileset(dir: libPath, includes: '**/*.jar')
fileset(dir: ".", includes: "**/*.jar")
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
classes.dependsOn('clean')
task copyFiles(type: Copy, dependsOn: 'classes') {
from outputPath
into "$projectDir/classes"
}
task preJar(type: Copy, dependsOn: guard ? 'compile_encrypt_javas' : 'compile_plain_javas') {
from "$projectDir/classes"
into "$projectDir/transform-classes"
include "**/*.*"
}
jar.dependsOn("preJar")
classes.dependsOn("copyPluginXML")
task copyPluginXML(type: Copy) {
print "copyed plugin.xml file"
from "$projectDir/plugin.xml"
into file("$projectDir/../webroot/WEB-INF/plugins/plugin-" + pluginName + "-1.0/")
}
task makeJar(type: Jar, dependsOn: preJar) {
delete file("$projectDir/classes")
delete file("$projectDir/transform-classes")
from fileTree(dir: "$projectDir/transform-classes")
baseName pluginPre
appendix pluginName
version pluginVersion
destinationDir = file("$buildDir/libs")
doLast() {
delete file("$projectDir/classes")
delete file("$projectDir/transform-classes")
}
}
task copyFile(type: Copy, dependsOn: ["makeJar"]) {
from "$buildDir/libs"
from("$projectDir/lib") {
include "*.jar"
}
from "$projectDir/plugin.xml"
into file("$buildDir/temp/plugin")
}
task zip(type: Zip, dependsOn: ["copyFile"]) {
from "$buildDir/temp/plugin"
destinationDir file("$buildDir/install")
baseName pluginPre
appendix pluginName
version pluginVersion
}
//build时包含哪些文件,
processResources {
// exclude everything
// *.css没效果
// exclude '**/*.css'
// except this file
// include 'xx.xml'
}
/*读取plugin.xml中的version*/
def getPluginInfo() {
def xmlFile = file("plugin.xml")
if (!xmlFile.exists()) {
return ["id": "none", "version": "1.0.0"]
}
def plugin = new XmlParser().parse(xmlFile)
def version = plugin.version[0].text()
def id = plugin.id[0].text()
return ["id": id, "version": version]
}
repositories {
mavenLocal()
maven {
url = uri('http://mvn.finedevelop.com/repository/maven-public/')
}
}
dependencies {
implementation 'org.projectlombok:lombok:1.18.20'
//使jar
implementation fileTree(dir: 'lib', include: ['**/*.jar'])
implementation fileTree(dir: libPath, include: ['**/*.jar'])
}

13
encrypt.xml

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project>
<target name="compile_encrypt_javas" depends="copyFiles">
<echo message="加密文件"/>
<echo message="${projectDir}"/>
<taskdef name="pretreatment" classname="com.fr.plugin.pack.PluginPretreatmentTask">
<classpath refid="compile.classpath"/>
</taskdef>
<pretreatment baseDir="${projectDir}"/>
</target>
<target name="compile_plain_javas" depends="copyFiles">
</target>
</project>

BIN
lib/DesSecurity.jar

Binary file not shown.

BIN
lib/commons-beanutils-1.9.4.jar

Binary file not shown.

BIN
lib/commons-collections-3.2.2.jar

Binary file not shown.

BIN
lib/commons-lang-2.6.jar

Binary file not shown.

BIN
lib/commons-logging-1.2.jar

Binary file not shown.

BIN
lib/ezmorph-1.0.6.jar

Binary file not shown.

BIN
lib/json-lib-2.4-jdk15.jar

Binary file not shown.

25
plugin.xml

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.fr.plugin.function.authLogin</id>
<name><![CDATA[台州银行驾驶舱项目 单点登录及统一身份认证]]></name>
<active>yes</active>
<version>1.0</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>liunb</vendor>
<description><![CDATA[台州银行驾驶舱项目 单点登录及统一身份认证]]></description>
<change-notes><![CDATA[
[2018-07-31]初始化插件。<br/>
]]></change-notes>
<!-- 单点登录及统一身份认证拦截器 -->
<extra-decision>
<GlobalRequestFilterProvider class="com.fr.plugin.decision.auth.filter.AuthLoginRequestFilter"/>
<GlobalRequestFilterProvider class="com.fr.plugin.decision.auth.filter.SsoLoginRequestFilter"/>
</extra-decision>
<!-- 插件功能点 -->
<function-recorder class="com.fr.plugin.decision.auth.LoginPluginLifecycle"/>
<!-- 插件生命周期声明 -->
<lifecycle-monitor class="com.fr.plugin.decision.auth.LoginPluginLifecycle"/>
</plugin>

22
src/main/java/com/fr/plugin/decision/auth/LoginPluginLifecycle.java

@ -0,0 +1,22 @@
package com.fr.plugin.decision.auth;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.decision.auth.config.AuthLoginPluginConfig;
import com.fr.plugin.decision.auth.config.SsoLoginPluginConfig;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
import com.fr.plugin.transform.FunctionRecorder;
@FunctionRecorder
public class LoginPluginLifecycle extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
SsoLoginPluginConfig.getInstance();
AuthLoginPluginConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

61
src/main/java/com/fr/plugin/decision/auth/RequestReaderHttpServletRequestWrapper.java

@ -0,0 +1,61 @@
package com.fr.plugin.decision.auth;
import com.fr.plugin.decision.auth.utils.FRUtils;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class RequestReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] body;
public RequestReaderHttpServletRequestWrapper(HttpServletRequest request) throws Exception {
super(request);
body = FRUtils.getBodyString(request).getBytes(Charset.forName("UTF-8"));
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
public String getBody() {
return new String(body, Charset.forName("UTF-8"));
}
}

100
src/main/java/com/fr/plugin/decision/auth/config/AuthLoginPluginConfig.java

@ -0,0 +1,100 @@
package com.fr.plugin.decision.auth.config;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
@Visualization(category = "统一身份认证参数配置")
public class AuthLoginPluginConfig extends DefaultConfiguration {
private static volatile AuthLoginPluginConfig config = null;
public static AuthLoginPluginConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(AuthLoginPluginConfig.class);
}
return config;
}
@Identifier(value = "serviceCode", name = "服务代码", description = "服务代码", status = Status.SHOW)
private Conf<String> serviceCode = Holders.simple("11002000002");
@Identifier(value = "serviceScene", name = "服务场景", description = "服务场景", status = Status.SHOW)
private Conf<String> serviceScene = Holders.simple("01");
@Identifier(value = "consumerId", name = "消费系统ID", description = "消费系统ID", status = Status.SHOW)
private Conf<String> consumerId = Holders.simple("406100");
@Identifier(value = "consumerSeqNo", name = "消费顺序号码", description = "消费顺序号码", status = Status.SHOW)
private Conf<String> consumerSeqNo = Holders.simple("01G4HNQ8YQDWQSKAHVSB31A6CQ");
@Identifier(value = "systemNo", name = "系统编码", description = "系统编码", status = Status.SHOW)
private Conf<String> systemNo = Holders.simple("bizpm");
@Identifier(value = "url", name = "请求URL", description = "请求URL", status = Status.SHOW)
private Conf<String> url = Holders.simple("http://10.1.136.170:11016/BIZPM");
public String getServiceCode() {
return serviceCode.get();
}
public void setServiceCode(String serviceCode) {
this.serviceCode.set(serviceCode);
}
public String getServiceScene() {
return serviceScene.get();
}
public void setServiceScene(String serviceScene) {
this.serviceScene.set(serviceScene);
}
public String getConsumerId() {
return consumerId.get();
}
public void setConsumerId(String consumerId) {
this.consumerId.set(consumerId);
}
public String getConsumerSeqNo() {
return consumerSeqNo.get();
}
public void setConsumerSeqNo(String consumerSeqNo) {
this.consumerSeqNo.set(consumerSeqNo);
}
public String getSystemNo() {
return systemNo.get();
}
public void setSystemNo(String systemNo) {
this.systemNo.set(systemNo);
}
public String getUrl() {
return url.get();
}
public void setUrl(String url) {
this.url.set(url);
}
@Override
public Object clone() throws CloneNotSupportedException {
AuthLoginPluginConfig cloned = (AuthLoginPluginConfig) super.clone();
cloned.serviceCode = (Conf<String>) serviceCode.clone();
cloned.serviceScene = (Conf<String>) serviceScene.clone();
cloned.consumerId = (Conf<String>) consumerId.clone();
cloned.consumerSeqNo = (Conf<String>) consumerSeqNo.clone();
cloned.systemNo = (Conf<String>) systemNo.clone();
cloned.url = (Conf<String>) url.clone();
return cloned;
}
}

100
src/main/java/com/fr/plugin/decision/auth/config/SsoLoginPluginConfig.java

@ -0,0 +1,100 @@
package com.fr.plugin.decision.auth.config;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
@Visualization(category = "单点登录参数配置")
public class SsoLoginPluginConfig extends DefaultConfiguration {
private static volatile SsoLoginPluginConfig config = null;
public static SsoLoginPluginConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(SsoLoginPluginConfig.class);
}
return config;
}
@Identifier(value = "serviceCode", name = "服务代码", description = "服务代码", status = Status.SHOW)
private Conf<String> serviceCode = Holders.simple("11002000152");
@Identifier(value = "serviceScene", name = "服务场景", description = "服务场景", status = Status.SHOW)
private Conf<String> serviceScene = Holders.simple("01");
@Identifier(value = "consumerId", name = "消费系统ID", description = "消费系统ID", status = Status.SHOW)
private Conf<String> consumerId = Holders.simple("401020");
@Identifier(value = "targetSysId", name = "目标系统ID", description = "目标系统ID", status = Status.SHOW)
private Conf<String> targetSysId = Holders.simple("401020");
@Identifier(value = "systemNo", name = "系统编码", description = "系统编码", status = Status.SHOW)
private Conf<String> systemNo = Holders.simple("hr");
@Identifier(value = "url", name = "请求URL", description = "请求URL", status = Status.SHOW)
private Conf<String> url = Holders.simple("http://10.1.136.170:11016/BIZPM");
public String getServiceCode() {
return serviceCode.get();
}
public void setServiceCode(String serviceCode) {
this.serviceCode.set(serviceCode);
}
public String getServiceScene() {
return serviceScene.get();
}
public void setServiceScene(String serviceScene) {
this.serviceScene.set(serviceScene);
}
public String getConsumerId() {
return consumerId.get();
}
public void setConsumerId(String consumerId) {
this.consumerId.set(consumerId);
}
public String getTargetSysId() {
return targetSysId.get();
}
public void setTargetSysId(String targetSysId) {
this.targetSysId.set(targetSysId);
}
public String getSystemNo() {
return systemNo.get();
}
public void setSystemNo(String systemNo) {
this.systemNo.set(systemNo);
}
public String getUrl() {
return url.get();
}
public void setUrl(String url) {
this.url.set(url);
}
@Override
public Object clone() throws CloneNotSupportedException {
SsoLoginPluginConfig cloned = (SsoLoginPluginConfig) super.clone();
cloned.serviceCode = (Conf<String>) serviceCode.clone();
cloned.serviceScene = (Conf<String>) serviceScene.clone();
cloned.consumerId = (Conf<String>) consumerId.clone();
cloned.targetSysId = (Conf<String>) targetSysId.clone();
cloned.systemNo = (Conf<String>) systemNo.clone();
cloned.url = (Conf<String>) url.clone();
return cloned;
}
}

546
src/main/java/com/fr/plugin/decision/auth/filter/AuthLoginRequestFilter.java

@ -0,0 +1,546 @@
package com.fr.plugin.decision.auth.filter;
import Com.Zstar.UUMS.Pub.DesSecurity;
import com.fr.base.ServerConfig;
import com.fr.base.TemplateUtils;
import com.fr.base.email.EmailCenter;
import com.fr.cbb.general.GeneralUtils;
import com.fr.data.NetworkHelper;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.data.CustomRole;
import com.fr.decision.authority.data.User;
import com.fr.decision.config.FSConfig;
import com.fr.decision.config.LoginVerificationConfig;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.mobile.terminal.TerminalHandler;
import com.fr.decision.privilege.TransmissionTool;
import com.fr.decision.record.LoginMessage;
import com.fr.decision.webservice.bean.authentication.LoginClientBean;
import com.fr.decision.webservice.bean.authentication.LoginResponseInfoBean;
import com.fr.decision.webservice.bean.authentication.OriginUrlResponseBean;
import com.fr.decision.webservice.utils.ControllerFactory;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.decision.webservice.utils.WebServiceUtils;
import com.fr.decision.webservice.utils.controller.AuthenticController;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.password.strategy.PasswordStrategyService;
import com.fr.decision.webservice.v10.sms.SMSService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.auth.RequestReaderHttpServletRequestWrapper;
import com.fr.plugin.decision.auth.config.AuthLoginPluginConfig;
import com.fr.security.TokenProcessorManager;
import com.fr.stable.StableUtils;
import com.fr.stable.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.web.Device;
import com.fr.store.Converter;
import com.fr.third.org.apache.commons.lang3.time.DateFormatUtils;
import com.fr.third.org.apache.http.HttpStatus;
import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse;
import com.fr.third.org.apache.http.client.methods.HttpPost;
import com.fr.third.org.apache.http.entity.StringEntity;
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient;
import com.fr.third.org.apache.http.impl.client.HttpClients;
import com.fr.third.org.apache.http.util.EntityUtils;
import com.fr.web.utils.WebUtils;
import net.sf.json.JSONObject;
import java.io.PrintWriter;
import java.util.*;
public class AuthLoginRequestFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "AuthLoginFilter";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision/login"
};
}
/**
* 实现统一身份认证拦截处理
* @param req
* @param res
* @param filterChain
*/
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
// 获取请求中的流如何,将取出来的字符串,再次转换成流,然后把它放入到新request对象中。
RequestReaderHttpServletRequestWrapper requestWrapper
= new RequestReaderHttpServletRequestWrapper((HttpServletRequest) req);
String body = requestWrapper.getBody();
// 验证请求
boolean bolRet = true;
if (StringUtils.isNotEmpty(body)) {
JSONObject bodyJson = JSONObject.fromObject(body);
// 用户名
String username = bodyJson.getString("username");
// 系统管理员 保留帆软验证
if ("admin".equals(username)) {
filterChain.doFilter(requestWrapper, res);
return;
}
// 加密后密码
String encPassword = bodyJson.getString("password");
String origin = GeneralUtils.objectToString(bodyJson.get("origin"));
int validity = bodyJson.getInt("validity");
// 帆软解密密码
String password = TransmissionTool.decrypt(encPassword);
// 统一身份认证
String responseStr = getUserInfo(username, password, "tzbank");
if (responseStr == null) {
responseStr = getUserInfo(username, password, "czbank");
}
if (responseStr != null) {
JSONObject resData = JSONObject.fromObject(responseStr);
if ("S".equals(resData.getJSONObject("SYS_HEAD").getString("RET_STATUS"))
&& "000000".equals(resData.getJSONObject("SYS_HEAD").getJSONArray("RET").getJSONObject(0).getString("RET_CODE"))) {
UserService userService = UserService.getInstance();
User user = userService.getUserByUserName(username);
if (user != null) {
String frToken = LoginService.getInstance().login(requestWrapper, res, username);
requestWrapper.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, frToken);
// 以下部分参考 LoginService.login 方法 START
OriginUrlResponseBean url = null;
if (StringUtils.isNotEmpty(origin)) {
url = (OriginUrlResponseBean) DecisionStatusService.originUrlStatusService().get(origin);
DecisionStatusService.originUrlStatusService().delete(origin);
if (url == null) {
url = new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}"));
}
} else {
url = new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}"));
}
Device device = NetworkHelper.getDevice(req);
String ip = WebServiceUtils.getIpInfoFromRequest(req);
TerminalHandler terminal = TerminalHandler.getTerminal(req, device);
AuthenticController authenticController = ControllerFactory.getInstance().getAuthenticController(user.getId());
long tokenTimeout = this.getTokenTimeOutByValidity(validity);
String token = this.generateToken(user, tokenTimeout);
authenticController.verifySingleLoginStatus(user.getUserName(), terminal, token);
if (authenticController.passwordChangeable(user)) {
PasswordStrategyService.getInstance().checkPasswordNeedUpdate(user, token);
}
LoginClientBean clientBean = new LoginClientBean(req, device, terminal);
clientBean.setUsername(user.getUserName());
clientBean.setToken(token);
clientBean.setValidity(validity);
clientBean.setUserId(user.getId());
authenticController.logoutSingleLoginInvalidUser(user.getUserName(), terminal);
this.addLoginStatus(token, clientBean, tokenTimeout);
LoginService.getInstance().checkServerInitStatus();
this.createLoginMessage(ip, user.getUserName(), user.getId());
if (ServerConfig.getInstance().isTokenFromCookie()) {
this.writeToken2Cookie(res, token, validity);
}
LoginResponseInfoBean responseInfoBean = new LoginResponseInfoBean(token, url, user.getUserName(), validity);
// 以上部分参考 LoginService.login 方法 END
com.fr.json.JSONObject data = buildResponseValue(responseInfoBean);
WebUtils.printAsJSON(res, data);
return;
} else {
bolRet = false;
}
} else {
bolRet = false;
}
} else {
bolRet = false;
}
}
if (!bolRet) {
// 统一身份认证请求失败 用户名或密码错误
JSONObject object = new JSONObject();
PrintWriter pw;
object.put("errorCode", "21300007");
object.put("errorMsg", "User not exist, or wrong password!");
pw = WebUtils.createPrintWriter(res);
res.setContentType("application/json;charset=utf-8");
String result = object.toString();
pw.println(result);
pw.flush();
pw.close();
return;
}
filterChain.doFilter(requestWrapper, res);
} catch (Exception e) {
e.printStackTrace();
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
}
private String getUserInfo(String username, String password, String bankType) {
// 配置参数
AuthLoginPluginConfig authLoginPluginConfig = AuthLoginPluginConfig.getInstance();
// 服务代码
String serviceCode = authLoginPluginConfig.getServiceCode();
// 服务场景
String serviceScene = authLoginPluginConfig.getServiceScene();
// 消费系统ID
String consumerId = authLoginPluginConfig.getConsumerId();
// 消费顺序号码
String consumerSeqNo = authLoginPluginConfig.getConsumerSeqNo();
// 系统编码
String systemNo = authLoginPluginConfig.getSystemNo();
// 请求URL
String postUrl = authLoginPluginConfig.getUrl();
Req request = new Req();
SYS_HEAD sysHeader = new SYS_HEAD();
APP_HEAD appHeader = new APP_HEAD();
Certificate_BODY BODY = new Certificate_BODY();
request.setSYS_HEAD(sysHeader);
request.setAPP_HEAD(appHeader);
request.setBODY(BODY);
String yyyyMMddHHmmssSSS = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS");
sysHeader.setCONSUMER_ID(consumerId);
sysHeader.setCONSUMER_SEQ_NO(consumerSeqNo);
sysHeader.setSERVICE_CODE(serviceCode);
sysHeader.setSERVICE_SCENE(serviceScene);
sysHeader.setTRAN_DATE(yyyyMMddHHmmssSSS.substring(0, 8));
sysHeader.setTRAN_TIMESTAMP(yyyyMMddHHmmssSSS.substring(8, 17));
BODY.setSYSTEM_NO(systemNo);
BODY.setBANK_SYSTEM_TYPE(bankType);
BODY.setUSER_ID(username);
DesSecurity desSecurity = new DesSecurity();
BODY.setUSER_PASSWORD(desSecurity.pinEncrypt(password));
sysHeader.setUSER_ID(username);
DesSecurity ds = new DesSecurity();
sysHeader.setUSER_PASSWORD(ds.pinEncrypt(password));
String reqStr = JSONObject.fromObject(request).toString();
FineLoggerFactory.getLogger().info("reqStr=" + reqStr);
StringEntity sn = new StringEntity(reqStr, "utf-8");
HttpPost post = new HttpPost(postUrl);
post.addHeader("Content-Type", "application/json");
post.setEntity(sn);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String responseStr = null;
try {
response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
FineLoggerFactory.getLogger().info("statusCode=" + statusCode);
FineLoggerFactory.getLogger().info("responseStr=" + responseStr);
JSONObject resData = JSONObject.fromObject(responseStr);
if (statusCode != HttpStatus.SC_OK) {
responseStr = null;
} else {
// 用户不存在
if ("4444".equals(resData.getJSONObject("SYS_HEAD").getJSONArray("RET").getJSONObject(0).getString("RET_CODE"))) {
responseStr = null;
}
}
} catch (Exception e) {
e.printStackTrace();
FineLoggerFactory.getLogger().error(e.getMessage(), e);
}
return responseStr;
}
private long getTokenTimeOutByValidity(int validity) {
return validity == -2 ? 1209600000L : FSConfig.getInstance().getLoginConfig().getLoginTimeout();
}
private String generateToken(User user, long timeOut) {
return this.generateToken(user.getUserName(), user.getDisplayName(), user.getTenantId(), timeOut);
}
private String generateToken(String username, String displayName, String tenantId, long timeOut) {
Map<String, Object> claims = new HashMap();
claims.put("description", displayName);
claims.put("tenantId", tenantId);
return TokenProcessorManager.getCurrentProcessor().generateToken(username, claims, timeOut);
}
private void addLoginStatus(String token, LoginClientBean clientBean, long tokenTimeout) throws Exception {
DecisionStatusService.loginStatusService().put(token, clientBean, new Converter<LoginClientBean>() {
public String[] createAlias(LoginClientBean loginClientBean) {
return new String[]{loginClientBean.getUsername()};
}
}, tokenTimeout);
}
private LoginMessage createLoginMessage(String ip, String username, String userId) throws Exception {
return LoginMessage.build(ip, username, this.getUserRole(userId));
}
private boolean needLoginVerification(Device device) {
if (device.isMobile()) {
return LoginVerificationConfig.getInstance().isSmsVerification() && SMSService.getInstance().isSMSAvailable();
} else {
return LoginVerificationConfig.getInstance().isSmsVerification() && SMSService.getInstance().isSMSAvailable() || LoginVerificationConfig.getInstance().isEmailVerification() && EmailCenter.isDefaultEmailConfigValid();
}
}
private String getUserRole(String userId) throws Exception {
List<String> customRoleName = new ArrayList();
List<CustomRole> customRoles = AuthorityContext.getInstance().getCustomRoleController().findByUser(userId, QueryFactory.create());
if (customRoles != null && !customRoles.isEmpty()) {
Iterator var4 = customRoles.iterator();
while(var4.hasNext()) {
CustomRole customRole = (CustomRole)var4.next();
customRoleName.add(customRole.getName());
}
}
return customRoleName.isEmpty() ? "" : StableUtils.join(customRoleName, ",");
}
private void writeToken2Cookie(HttpServletResponse response, String token, int validity) {
try {
if (StringUtils.isNotEmpty(token)) {
Cookie cookie = new Cookie("fine_auth_token", token);
long cookieLife = validity == -2 ? 1209600000L : (long)validity;
cookie.setMaxAge((int)cookieLife);
cookie.setPath(ServerConfig.getInstance().getCookiePath());
response.addCookie(cookie);
Cookie rememberLogin = new Cookie("fine_remember_login", String.valueOf(validity == -2 ? -2 : -1));
rememberLogin.setMaxAge((int)cookieLife);
rememberLogin.setPath(ServerConfig.getInstance().getCookiePath());
response.addCookie(rememberLogin);
} else {
FineLoggerFactory.getLogger().error("empty token cannot save.");
}
} catch (Exception var8) {
FineLoggerFactory.getLogger().error(var8.getMessage(), var8);
}
}
private static com.fr.json.JSONObject buildResponseValue(LoginResponseInfoBean responseInfoBean){
com.fr.json.JSONObject data = new com.fr.json.JSONObject();
data.put("username",responseInfoBean.getUsername());
data.put("validity",responseInfoBean.getValidity());
data.put("callback",responseInfoBean.getCallback());
data.put("accessToken",responseInfoBean.getAccessToken());
OriginUrlResponseBean originUrlResponse = responseInfoBean.getOriginUrlResponse();
JSONObject originUrlJson = new JSONObject();
originUrlJson.put("originUrl",originUrlResponse.getOriginUrl());
originUrlJson.put("method",originUrlResponse.getMethod());
originUrlJson.put("parameters",originUrlResponse.getParameters());
data.put("originUrlResponse",originUrlJson);
data.put("url",responseInfoBean.getUrl());
return new com.fr.json.JSONObject().put("data",data);
}
public static class Req<T> {
private SYS_HEAD SYS_HEAD;
private APP_HEAD APP_HEAD;
private T BODY;
public SYS_HEAD getSYS_HEAD() {
return SYS_HEAD;
}
public void setSYS_HEAD(SYS_HEAD SYS_HEAD) {
this.SYS_HEAD = SYS_HEAD;
}
public APP_HEAD getAPP_HEAD() {
return APP_HEAD;
}
public void setAPP_HEAD(APP_HEAD APP_HEAD) {
this.APP_HEAD = APP_HEAD;
}
public T getBODY() {
return BODY;
}
public void setBODY(T BODY) {
this.BODY = BODY;
}
}
public static class SYS_HEAD {
private String SERVICE_CODE;
private String SERVICE_SCENE;
private String CONSUMER_ID;
private String TRAN_DATE;
private String TRAN_TIMESTAMP;
private String CONSUMER_SEQ_NO;
private String USER_ID;
private String USER_PASSWORD;
public String getSERVICE_CODE() {
return SERVICE_CODE;
}
public void setSERVICE_CODE(String SERVICE_CODE) {
this.SERVICE_CODE = SERVICE_CODE;
}
public String getSERVICE_SCENE() {
return SERVICE_SCENE;
}
public void setSERVICE_SCENE(String SERVICE_SCENE) {
this.SERVICE_SCENE = SERVICE_SCENE;
}
public String getCONSUMER_ID() {
return CONSUMER_ID;
}
public void setCONSUMER_ID(String CONSUMER_ID) {
this.CONSUMER_ID = CONSUMER_ID;
}
public String getTRAN_DATE() {
return TRAN_DATE;
}
public void setTRAN_DATE(String TRAN_DATE) {
this.TRAN_DATE = TRAN_DATE;
}
public String getTRAN_TIMESTAMP() {
return TRAN_TIMESTAMP;
}
public void setTRAN_TIMESTAMP(String TRAN_TIMESTAMP) {
this.TRAN_TIMESTAMP = TRAN_TIMESTAMP;
}
public String getCONSUMER_SEQ_NO() {
return CONSUMER_SEQ_NO;
}
public void setCONSUMER_SEQ_NO(String CONSUMER_SEQ_NO) {
this.CONSUMER_SEQ_NO = CONSUMER_SEQ_NO;
}
public String getUSER_ID() {
return USER_ID;
}
public void setUSER_ID(String USER_ID) {
this.USER_ID = USER_ID;
}
public String getUSER_PASSWORD() {
return USER_PASSWORD;
}
public void setUSER_PASSWORD(String USER_PASSWORD) {
this.USER_PASSWORD = USER_PASSWORD;
}
}
public static class APP_HEAD {
}
public static class Certificate_BODY {
private String BANK_SYSTEM_TYPE;
private String SYSTEM_NO;
private String USER_ID;
private String USER_PASSWORD;
public String getBANK_SYSTEM_TYPE() {
return BANK_SYSTEM_TYPE;
}
public void setBANK_SYSTEM_TYPE(String BANK_SYSTEM_TYPE) {
this.BANK_SYSTEM_TYPE = BANK_SYSTEM_TYPE;
}
public String getSYSTEM_NO() {
return SYSTEM_NO;
}
public void setSYSTEM_NO(String SYSTEM_NO) {
this.SYSTEM_NO = SYSTEM_NO;
}
public String getUSER_ID() {
return USER_ID;
}
public void setUSER_ID(String USER_ID) {
this.USER_ID = USER_ID;
}
public String getUSER_PASSWORD() {
return USER_PASSWORD;
}
public void setUSER_PASSWORD(String USER_PASSWORD) {
this.USER_PASSWORD = USER_PASSWORD;
}
}
}

286
src/main/java/com/fr/plugin/decision/auth/filter/SsoLoginRequestFilter.java

@ -0,0 +1,286 @@
package com.fr.plugin.decision.auth.filter;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.decision.auth.config.SsoLoginPluginConfig;
import com.fr.third.org.apache.http.HttpStatus;
import com.fr.third.org.apache.http.client.methods.CloseableHttpResponse;
import com.fr.third.org.apache.http.client.methods.HttpPost;
import com.fr.third.org.apache.http.entity.StringEntity;
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient;
import com.fr.third.org.apache.http.impl.client.HttpClients;
import com.fr.third.org.apache.http.util.EntityUtils;
import com.fr.web.utils.WebUtils;
import net.sf.json.JSONObject;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SsoLoginRequestFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "SsoLoginFilter";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision/ssoLogin"
};
}
/**
* 实现单点登录拦截处理
* @param req
* @param res
* @param filterChain
*/
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
String url = WebUtils.getOriginalURL(req);
if (url.contains("decision/ssoLogin")) {
// token参数值
String token = req.getParameter("token");
// 配置参数
SsoLoginPluginConfig ssoLoginPluginConfig = SsoLoginPluginConfig.getInstance();
// 服务代码
String serviceCode = ssoLoginPluginConfig.getServiceCode();
// 服务场景
String serviceScene = ssoLoginPluginConfig.getServiceScene();
// 消费系统ID
String consumerId = ssoLoginPluginConfig.getConsumerId();
// 目标系统ID
String targetSysId = ssoLoginPluginConfig.getTargetSysId();
// 系统编码
String systemNo = ssoLoginPluginConfig.getSystemNo();
// 请求URL
String postUrl = ssoLoginPluginConfig.getUrl();
Req<SINGLE_LOGIN_BODY> request = new Req();
SYS_HEAD sysHeader = new SYS_HEAD();
APP_HEAD appHeader = new APP_HEAD();
SINGLE_LOGIN_BODY BODY = new SINGLE_LOGIN_BODY();
request.setSYS_HEAD(sysHeader);
request.setAPP_HEAD(appHeader);
request.setBODY(BODY);
sysHeader.setCONSUMER_ID(consumerId);
sysHeader.setSERVICE_CODE(serviceCode);
sysHeader.setSERVICE_SCENE(serviceScene);
sysHeader.setTARGET_SYS_ID(targetSysId);
BODY.setSYSTEM_NO(systemNo);
BODY.setTOKEN_NO(token);
String reqStr = JSONObject.fromObject(request).toString();
FineLoggerFactory.getLogger().info("reqStr=" + reqStr);
StringEntity sn = new StringEntity(reqStr, "utf-8");
HttpPost post = new HttpPost(postUrl);
post.addHeader("Content-Type","application/json");
post.setEntity(sn);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String responseStr = EntityUtils.toString(response.getEntity(), "utf-8");
FineLoggerFactory.getLogger().info("statusCode=" + statusCode);
FineLoggerFactory.getLogger().info("responseStr=" + responseStr);
if (statusCode != HttpStatus.SC_OK) {
FineLoggerFactory.getLogger().error("TOKEN验证请求失败");
WebUtils.printAsString(res, "TOKEN验证请求失败");
return;
}
JSONObject resData = JSONObject.fromObject(responseStr);
if ("S".equals(resData.getJSONObject("SYS_HEAD").getString("RET_STATUS"))
&& "000000".equals(resData.getJSONObject("SYS_HEAD").getJSONArray("RET").getJSONObject(0).getString("RET_CODE"))) {
// 用户名
String userName = "";
if (resData.getJSONObject("BODY").getString("LOGON_ID") != null) {
userName = resData.getJSONObject("BODY").getString("LOGON_ID").trim();
}
FineLoggerFactory.getLogger().info("userName:" + userName);
UserService userService = UserService.getInstance();
User user = userService.getUserByUserName(userName);
if (user != null) {
String frToken = LoginService.getInstance().login(req, res, userName);
req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, frToken);
String newUrl = url.substring(0, url.indexOf("/ssoLogin"));
res.sendRedirect(newUrl);
return;
} else {
FineLoggerFactory.getLogger().error("获取的用户 :{} 在帆软系统中不存在", userName);
WebUtils.printAsString(res, "获取的用户 : " + userName + "在帆软系统中不存在");
return;
}
} else {
FineLoggerFactory.getLogger().error("TOKEN验证请求失败");
WebUtils.printAsString(res, "TOKEN验证请求失败");
return;
}
}
filterChain.doFilter(req, res);
} catch (Exception e) {
e.printStackTrace();
FineLoggerFactory.getLogger().error(e.getMessage(), e);
try {
WebUtils.printAsString(res, "TOKEN验证请求失败");
} catch (Exception ex) {
}
}
}
public static class Req<T> {
private SYS_HEAD SYS_HEAD;
private APP_HEAD APP_HEAD;
private T BODY;
public SYS_HEAD getSYS_HEAD() {
return SYS_HEAD;
}
public void setSYS_HEAD(SYS_HEAD SYS_HEAD) {
this.SYS_HEAD = SYS_HEAD;
}
public APP_HEAD getAPP_HEAD() {
return APP_HEAD;
}
public void setAPP_HEAD(APP_HEAD APP_HEAD) {
this.APP_HEAD = APP_HEAD;
}
public T getBODY() {
return BODY;
}
public void setBODY(T BODY) {
this.BODY = BODY;
}
}
public static class SYS_HEAD {
private String SERVICE_CODE;
private String SERVICE_SCENE;
private String CONSUMER_ID;
private String TARGET_SYS_ID;
public String getSERVICE_CODE() {
return SERVICE_CODE;
}
public void setSERVICE_CODE(String SERVICE_CODE) {
this.SERVICE_CODE = SERVICE_CODE;
}
public String getSERVICE_SCENE() {
return SERVICE_SCENE;
}
public void setSERVICE_SCENE(String SERVICE_SCENE) {
this.SERVICE_SCENE = SERVICE_SCENE;
}
public String getCONSUMER_ID() {
return CONSUMER_ID;
}
public void setCONSUMER_ID(String CONSUMER_ID) {
this.CONSUMER_ID = CONSUMER_ID;
}
public String getTARGET_SYS_ID() {
return TARGET_SYS_ID;
}
public void setTARGET_SYS_ID(String TARGET_SYS_ID) {
this.TARGET_SYS_ID = TARGET_SYS_ID;
}
}
public static class APP_HEAD {
}
public static class SINGLE_LOGIN_BODY {
private String TOKEN_NO;
private String SYSTEM_NO;
public String getTOKEN_NO() {
return TOKEN_NO;
}
public void setTOKEN_NO(String TOKEN_NO) {
this.TOKEN_NO = TOKEN_NO;
}
public String getSYSTEM_NO() {
return SYSTEM_NO;
}
public void setSYSTEM_NO(String SYSTEM_NO) {
this.SYSTEM_NO = SYSTEM_NO;
}
}
public static class SINGLE_LOGIN_RES_BODY {
private String LOGON_ID;
private String BANK_SYSTEM_TYPE;
private String PASSWORD;
public String getLOGON_ID() {
return LOGON_ID;
}
public void setLOGON_ID(String LOGON_ID) {
this.LOGON_ID = LOGON_ID;
}
public String getBANK_SYSTEM_TYPE() {
return BANK_SYSTEM_TYPE;
}
public void setBANK_SYSTEM_TYPE(String BANK_SYSTEM_TYPE) {
this.BANK_SYSTEM_TYPE = BANK_SYSTEM_TYPE;
}
public String getPASSWORD() {
return PASSWORD;
}
public void setPASSWORD(String PASSWORD) {
this.PASSWORD = PASSWORD;
}
}
}

28
src/main/java/com/fr/plugin/decision/auth/utils/FRUtils.java

@ -0,0 +1,28 @@
package com.fr.plugin.decision.auth.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class FRUtils {
/**
* 从req获取json字符串数据
*/
public static String getBodyString(HttpServletRequest request) throws Exception {
BufferedReader bf = new BufferedReader(new InputStreamReader(
request.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
String tmp;
while ((tmp = bf.readLine()) != null) {
sb.append(tmp);
}
bf.close();
return sb.toString();
}
}
Loading…
Cancel
Save