commit
21ba2c9937
14 changed files with 1781 additions and 0 deletions
@ -0,0 +1,6 @@
|
||||
# open-JSD-9784 |
||||
|
||||
JSD-9784 采用oidc方式实现单点登录\ |
||||
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ |
||||
仅作为开发者学习参考使用!禁止用于任何商业用途!\ |
||||
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 |
Binary file not shown.
@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin> |
||||
<id>com.eco.plugin.xx.addssso</id> |
||||
<name><![CDATA[单点登录]]></name> |
||||
<active>yes</active> |
||||
<version>1.0.14</version> |
||||
<env-version>10.0</env-version> |
||||
<jartime>2018-07-31</jartime> |
||||
<vendor>fr.open</vendor> |
||||
<description><![CDATA[单点登录]]></description> |
||||
<change-notes><![CDATA[ |
||||
]]></change-notes> |
||||
<main-package>com.eco.plugin.xx.addssso</main-package> |
||||
<lifecycle-monitor class="com.eco.plugin.xx.addssso.config.InitializeMonitor"/> |
||||
|
||||
<extra-decision> |
||||
<GlobalRequestFilterProvider class="com.eco.plugin.xx.addssso.filter.SSOFilter"/> |
||||
<LogInOutEventProvider class="com.eco.plugin.xx.addssso.logout.Logout"/> |
||||
</extra-decision> |
||||
|
||||
<function-recorder class="com.eco.plugin.xx.addssso.config.PluginSimpleConfig"/> |
||||
|
||||
</plugin> |
@ -0,0 +1,21 @@
|
||||
package com.eco.plugin.xx.addssso.config; |
||||
|
||||
import com.fr.plugin.context.PluginContext; |
||||
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor; |
||||
|
||||
/** |
||||
* @author xx |
||||
* @version 10.0 |
||||
* Created by xx on 2021-12-03 |
||||
*/ |
||||
public class InitializeMonitor extends AbstractPluginLifecycleMonitor { |
||||
@Override |
||||
public void afterRun(PluginContext pluginContext) { |
||||
PluginSimpleConfig.getInstance(); |
||||
} |
||||
|
||||
@Override |
||||
public void beforeStop(PluginContext pluginContext) { |
||||
|
||||
} |
||||
} |
@ -0,0 +1,101 @@
|
||||
package com.eco.plugin.xx.addssso.config; |
||||
|
||||
import com.fr.config.*; |
||||
import com.fr.config.holder.Conf; |
||||
import com.fr.config.holder.factory.Holders; |
||||
import com.fr.intelli.record.Focus; |
||||
import com.fr.intelli.record.Original; |
||||
import com.fr.record.analyzer.EnableMetrics; |
||||
|
||||
@Visualization(category = "单点登录配置") |
||||
@EnableMetrics |
||||
public class PluginSimpleConfig extends DefaultConfiguration { |
||||
|
||||
private static volatile PluginSimpleConfig config = null; |
||||
|
||||
@Focus(id="com.eco.plugin.xx.idmsso.config", text = "单点登录配置", source = Original.PLUGIN) |
||||
public static PluginSimpleConfig getInstance() { |
||||
if (config == null) { |
||||
config = ConfigContext.getConfigInstance(PluginSimpleConfig.class); |
||||
} |
||||
return config; |
||||
} |
||||
|
||||
@Identifier(value = "clientId", name = "应用id", description = "应用id", status = Status.SHOW) |
||||
private Conf<String> clientId = Holders.simple(""); |
||||
|
||||
@Identifier(value = "secret", name = "密钥", description = "密钥", status = Status.SHOW) |
||||
private Conf<String> secret = Holders.simple(""); |
||||
|
||||
@Identifier(value = "authUrl", name = "获取授权码接口", description = "获取授权码接口", status = Status.SHOW) |
||||
private Conf<String> authUrl = Holders.simple(""); |
||||
|
||||
@Identifier(value = "tokenUrl", name = "获取token接口", description = "获取token接口", status = Status.SHOW) |
||||
private Conf<String> tokenUrl = Holders.simple(""); |
||||
|
||||
@Identifier(value = "userurl", name = "获取证书接口", description = "获取证书接口", status = Status.SHOW) |
||||
private Conf<String> userurl = Holders.simple(""); |
||||
|
||||
@Identifier(value = "logoutUrl", name = "登出接口", description = "登出接口", status = Status.SHOW) |
||||
private Conf<String> logoutUrl = Holders.simple(""); |
||||
|
||||
public String getClientId() { |
||||
return clientId.get(); |
||||
} |
||||
|
||||
public void setClientId(String url) { |
||||
this.clientId.set(url); |
||||
} |
||||
|
||||
public String getSecret() { |
||||
return secret.get(); |
||||
} |
||||
|
||||
public void setSecret(String url) { |
||||
this.secret.set(url); |
||||
} |
||||
|
||||
public String getAuthUrl() { |
||||
return authUrl.get(); |
||||
} |
||||
|
||||
public void setAuthUrl(String url) { |
||||
this.authUrl.set(url); |
||||
} |
||||
|
||||
public String getTokenUrl() { |
||||
return tokenUrl.get(); |
||||
} |
||||
|
||||
public void setTokenUrl(String url) { |
||||
this.tokenUrl.set(url); |
||||
} |
||||
|
||||
public String getUserurl() { |
||||
return userurl.get(); |
||||
} |
||||
|
||||
public void setUserurl(String url) { |
||||
this.userurl.set(url); |
||||
} |
||||
|
||||
public String getLogoutUrl() { |
||||
return logoutUrl.get(); |
||||
} |
||||
|
||||
public void setLogoutUrl(String url) { |
||||
this.logoutUrl.set(url); |
||||
} |
||||
|
||||
@Override |
||||
public Object clone() throws CloneNotSupportedException { |
||||
PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone(); |
||||
// cloned.text = (Conf<String>) text.clone();
|
||||
// cloned.count = (Conf<Integer>) count.clone();
|
||||
// cloned.price = (Conf<Double>) price.clone();
|
||||
// cloned.time = (Conf<Long>) time.clone();
|
||||
// cloned.student = (Conf<Boolean>) student.clone();
|
||||
return cloned; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,207 @@
|
||||
package com.eco.plugin.xx.addssso.filter; |
||||
|
||||
import cn.hutool.jwt.JWT; |
||||
import cn.hutool.jwt.JWTPayload; |
||||
import cn.hutool.jwt.JWTUtil; |
||||
import com.eco.plugin.xx.addssso.config.PluginSimpleConfig; |
||||
import com.eco.plugin.xx.addssso.utils.FRUtils; |
||||
import com.eco.plugin.xx.addssso.utils.HttpUtils; |
||||
import com.eco.plugin.xx.addssso.utils.ResponseUtils; |
||||
import com.eco.plugin.xx.addssso.utils.Utils; |
||||
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.plugin.context.PluginContexts; |
||||
import com.fr.record.analyzer.EnableMetrics; |
||||
import com.fr.stable.fun.Authorize; |
||||
|
||||
import javax.servlet.FilterChain; |
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import java.io.IOException; |
||||
import java.net.URLEncoder; |
||||
import java.util.HashMap; |
||||
import java.util.Locale; |
||||
import java.util.Map; |
||||
|
||||
@EnableMetrics |
||||
@Authorize(callSignKey = "com.eco.plugin.xx.addssso") |
||||
public class SSOFilter extends AbstractGlobalRequestFilterProvider { |
||||
@Override |
||||
public String filterName() { |
||||
return "addsssoFilter"; |
||||
} |
||||
|
||||
@Override |
||||
public String[] urlPatterns() { |
||||
return new String[]{"/*"}; |
||||
} |
||||
|
||||
@Override |
||||
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){ |
||||
if(PluginContexts.currentContext().isAvailable()){ |
||||
PluginSimpleConfig psc = PluginSimpleConfig.getInstance(); |
||||
|
||||
//是否放行
|
||||
boolean release = isRelease(req); |
||||
|
||||
if(release){ |
||||
release(req,res,chain); |
||||
return; |
||||
} |
||||
|
||||
String code = req.getParameter("code"); |
||||
|
||||
String token = ""; |
||||
String username = ""; |
||||
|
||||
try{ |
||||
if(Utils.isNullStr(code)){ |
||||
//跳转认证中心
|
||||
redirect(req,res,psc); |
||||
return; |
||||
} |
||||
|
||||
//获取token
|
||||
token = getToken(req,code,psc); |
||||
|
||||
//获取userInfo
|
||||
username = getUsername(token); |
||||
}catch(Exception e){ |
||||
Utils.toErrorPage(res,"/com/eco/plugin/xx/addssso/error.html",null); |
||||
return ; |
||||
} |
||||
|
||||
|
||||
|
||||
String url = Utils.getRedirectUrl(req,"code"); |
||||
String viewlet = getTempId(req); |
||||
String result = syncAuth(username,token,url.split("decision")[0]+"decision/syncAuth",viewlet); |
||||
|
||||
if("2".equals(result)){ |
||||
ResponseUtils.failedResponse(res,"无权限查看"); |
||||
return ; |
||||
} |
||||
|
||||
if("3".equals(result)){ |
||||
ResponseUtils.failedResponse(res,"系统异常,请联系管理员"); |
||||
return ; |
||||
} |
||||
|
||||
//登录
|
||||
FRUtils.login(req,res,username,url); |
||||
} |
||||
|
||||
release(req,res,chain); |
||||
} |
||||
|
||||
private String getTempId(HttpServletRequest req){ |
||||
String viewlet = req.getParameter("viewlet"); |
||||
|
||||
if(Utils.isNullStr(viewlet)){ |
||||
String url = FRUtils.getAllUrl(req); |
||||
String[] array = url.split("/"); |
||||
viewlet = array[array.length-2]; |
||||
if(viewlet.length()!=32){ |
||||
viewlet = ""; |
||||
} |
||||
} |
||||
|
||||
|
||||
|
||||
return viewlet; |
||||
} |
||||
|
||||
private String syncAuth(String username,String token,String url,String viewlet) { |
||||
url += url.contains("?") ?"&email="+username : "?email="+username; |
||||
url += "&token="+token+"&tempId="+URLEncoder.encode(viewlet); |
||||
FRUtils.FRLogInfo("syncAuthUrl:"+url); |
||||
|
||||
String result = HttpUtils.HttpPostJson(url,null,null); |
||||
|
||||
JSONObject resultJson = new JSONObject(result); |
||||
|
||||
return resultJson.getString("data"); |
||||
|
||||
} |
||||
|
||||
private boolean isRelease(HttpServletRequest req) { |
||||
boolean release = false; |
||||
String token = req.getParameter("Token"); |
||||
String accout = req.getParameter("UserAccount"); |
||||
|
||||
if (!Utils.isNullStr(token) || !Utils.isNullStr(accout)) { |
||||
release = true; |
||||
} |
||||
String url = FRUtils.getAllUrl(req); |
||||
String reft = req.getParameter("ref_t"); |
||||
|
||||
boolean isLogin = FRUtils.isLogin(req); |
||||
boolean isRemote = url.contains("remote"); |
||||
boolean isLoginPage = url.contains("refreshMobileAuth")||url.contains("syncAuth") || url.contains("login")||url.contains("decision/file")||url.contains("decision/resource")||url.contains("decision/system")||url.contains("query/ip"); |
||||
// boolean isViewlt = url.contains("viewlet") || "design".equals(reft) || url.contains("view/report") || url.contains("view/form");
|
||||
boolean isViewlt = "design".equals(reft) ; |
||||
return isLogin || isRemote || isLoginPage || isViewlt || release; |
||||
} |
||||
|
||||
//跳转认证中心
|
||||
private void redirect(HttpServletRequest req,HttpServletResponse res, PluginSimpleConfig psc) { |
||||
String url = FRUtils.getAllUrl(req); |
||||
String authurl = psc.getAuthUrl()+"?response_type=code&client_id="+psc.getClientId()+"&redirect_uri="+URLEncoder.encode(url)+"&state=135caa68-2093-4f29-8234-89b8b5480d7a" ; |
||||
|
||||
try { |
||||
res.sendRedirect(authurl); |
||||
} catch (IOException e) { |
||||
FRUtils.FRLogInfo("跳转认证中心异常:"+e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
//获取token
|
||||
private String getToken(HttpServletRequest req,String code,PluginSimpleConfig psc) { |
||||
String tokenurl = psc.getTokenUrl(); |
||||
|
||||
String url = FRUtils.getAllUrl(req); |
||||
url = Utils.removeParam(url,"state"); |
||||
FRUtils.FRLogInfo("url:"+url); |
||||
Map<String,String> param = new HashMap<String,String>(); |
||||
param.put("client_id",psc.getClientId()); |
||||
param.put("client_secret",psc.getSecret()); |
||||
param.put("grant_type","authorization_code"); |
||||
param.put("code",code); |
||||
param.put("redirect_uri",url); |
||||
|
||||
|
||||
String result = HttpUtils.HttpPostWWWForm(tokenurl,null,param); |
||||
|
||||
if(Utils.isNullStr(result)){ |
||||
return ""; |
||||
} |
||||
|
||||
JSONObject json = new JSONObject(result); |
||||
|
||||
if(json == null ){ |
||||
return ""; |
||||
} |
||||
|
||||
String token = json.getString("access_token"); |
||||
return token; |
||||
} |
||||
|
||||
//获取用户名
|
||||
private String getUsername(String token) { |
||||
JWT jwt = JWTUtil.parseToken(token); |
||||
JWTPayload p = jwt.getPayload(); |
||||
String email = String.valueOf(p.getClaim("email")); |
||||
|
||||
return email.toLowerCase(Locale.ROOT); |
||||
} |
||||
|
||||
//放行拦截器
|
||||
private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) { |
||||
try{ |
||||
chain.doFilter(req,res); |
||||
}catch (Exception e){ |
||||
FRUtils.FRLogInfo("拦截失败"); |
||||
} |
||||
} |
||||
} |
||||
|
@ -0,0 +1,21 @@
|
||||
package com.eco.plugin.xx.addssso.logout; |
||||
|
||||
import com.eco.plugin.xx.addssso.config.PluginSimpleConfig; |
||||
import com.eco.plugin.xx.addssso.utils.FRUtils; |
||||
import com.fr.decision.fun.impl.AbstractLogInOutEventProvider; |
||||
import com.fr.decision.webservice.login.LogInOutResultInfo; |
||||
import com.fr.decision.webservice.v10.login.LoginService; |
||||
|
||||
import javax.servlet.http.HttpSession; |
||||
|
||||
public class Logout extends AbstractLogInOutEventProvider { |
||||
|
||||
@Override |
||||
public String logoutAction(LogInOutResultInfo result) { |
||||
HttpSession session = result.getRequest().getSession(true); |
||||
LoginService.getInstance().crossDomainLogout(result.getRequest(),result.getResponse(),""); |
||||
session.invalidate(); |
||||
return PluginSimpleConfig.getInstance().getLogoutUrl()+"?redirect="+FRUtils.getIndex(result.getRequest()); |
||||
} |
||||
} |
||||
|
@ -0,0 +1,331 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import sun.misc.BASE64Decoder; |
||||
import sun.misc.BASE64Encoder; |
||||
import javax.crypto.Cipher; |
||||
import javax.crypto.KeyGenerator; |
||||
import javax.crypto.SecretKey; |
||||
import javax.crypto.SecretKeyFactory; |
||||
import javax.crypto.spec.DESKeySpec; |
||||
import java.io.IOException; |
||||
import java.security.*; |
||||
import java.security.interfaces.RSAPrivateKey; |
||||
import java.security.interfaces.RSAPublicKey; |
||||
import java.security.spec.PKCS8EncodedKeySpec; |
||||
import java.security.spec.X509EncodedKeySpec; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
public class EncryptUtils { |
||||
|
||||
/** |
||||
* sha 加密 |
||||
* @param str |
||||
* @return |
||||
*/ |
||||
public static String sha(String str){ |
||||
String sha256Str = ""; |
||||
|
||||
try { |
||||
MessageDigest sha256Deget = MessageDigest.getInstance("SHA-256"); |
||||
byte[] sha256Encode = sha256Deget.digest(str.getBytes()); |
||||
sha256Str = ByteToHexStr(sha256Encode); |
||||
}catch (Exception e){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:SHA256加密异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return sha256Str; |
||||
} |
||||
|
||||
/** |
||||
* byte数组转16进制字符串 |
||||
* @param bytes |
||||
* @return |
||||
*/ |
||||
private static String ByteToHexStr(byte[] bytes) |
||||
{ |
||||
String hexStr = ""; |
||||
|
||||
for(int i =0;i<bytes.length;i++) |
||||
{ |
||||
int temp = bytes[i] & 0xff; |
||||
String tempHex = Integer.toHexString(temp); |
||||
if(tempHex.length() < 2) |
||||
{ |
||||
hexStr += "0"+tempHex; |
||||
} |
||||
else { |
||||
hexStr += tempHex; |
||||
} |
||||
} |
||||
|
||||
return hexStr; |
||||
} |
||||
|
||||
/** |
||||
* aes 加密 |
||||
* @param str |
||||
* @param privateKey |
||||
* @return |
||||
*/ |
||||
public static String aesEncrypt(String str,String privateKey){ |
||||
try { |
||||
// 生成密钥对象
|
||||
SecretKey secKey = generateAesKey(privateKey.getBytes()); |
||||
|
||||
// 获取 AES 密码器
|
||||
Cipher cipher = Cipher.getInstance("AES"); |
||||
// 初始化密码器(加密模型)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secKey); |
||||
|
||||
// 加密数据, 返回密文
|
||||
byte[] cipherBytes = cipher.doFinal(str.getBytes()); |
||||
return new BASE64Encoder().encodeBuffer(cipherBytes); |
||||
} catch (Throwable e) { |
||||
FRUtils.FRLogInfo("aes 加密异常 " + e.getMessage()); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
|
||||
/** |
||||
* 生成密钥对象 |
||||
*/ |
||||
private static SecretKey generateAesKey(byte[] key) throws Exception { |
||||
// 创建安全随机数生成器
|
||||
SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); |
||||
// 设置 密钥key的字节数组 作为安全随机数生成器的种子
|
||||
random.setSeed(key); |
||||
|
||||
// 创建 AES算法生成器
|
||||
KeyGenerator gen = KeyGenerator.getInstance("AES"); |
||||
// 初始化算法生成器
|
||||
gen.init(128, random); |
||||
|
||||
// 生成 AES密钥对象, 也可以直接创建密钥对象: return new SecretKeySpec(key, ALGORITHM);
|
||||
return gen.generateKey(); |
||||
} |
||||
|
||||
/** |
||||
* aes 解密 |
||||
* @param str |
||||
* @param privateKey |
||||
* @return |
||||
*/ |
||||
public static String aesDecrypt(String str,String privateKey){ |
||||
try { |
||||
// 生成密钥对象
|
||||
SecretKey secKey = generateAesKey(privateKey.getBytes()); |
||||
|
||||
// 获取 AES 密码器
|
||||
Cipher cipher = Cipher.getInstance("AES"); |
||||
// 初始化密码器(加密模型)
|
||||
cipher.init(Cipher.DECRYPT_MODE, secKey); |
||||
|
||||
// 加密数据, 返回密文
|
||||
byte[] cipherBytes = cipher.doFinal(new BASE64Decoder().decodeBuffer(str)); |
||||
return new String(cipherBytes); |
||||
} catch (Throwable e) { |
||||
FRUtils.FRLogInfo("aes 解密异常 " + e.getMessage()); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
|
||||
/** |
||||
* base64加密 |
||||
* @param key |
||||
* @return |
||||
*/ |
||||
public static String base64Encode(String key){ |
||||
return (new BASE64Encoder()).encodeBuffer(key.getBytes()); |
||||
} |
||||
|
||||
/** |
||||
* base64加密 |
||||
* @param key |
||||
* @return |
||||
*/ |
||||
public static String base64Encode(byte[] key){ |
||||
return (new BASE64Encoder()).encodeBuffer(key); |
||||
} |
||||
|
||||
/** |
||||
* base64解密 |
||||
* @param key |
||||
* @return |
||||
*/ |
||||
public static String base64Decode(String key){ |
||||
String result = ""; |
||||
try { |
||||
result = new String((new BASE64Decoder()).decodeBuffer(key)); |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:BASE64解密异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return result; |
||||
} |
||||
|
||||
/** |
||||
* base64解密 |
||||
* @param key |
||||
* @return |
||||
*/ |
||||
public static byte[] base64DecodeB(String key){ |
||||
byte[] result = null; |
||||
try { |
||||
result = (new BASE64Decoder()).decodeBuffer(key); |
||||
} catch (IOException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:BASE64解密异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return result; |
||||
} |
||||
|
||||
/** |
||||
* 是否被base64加密过 |
||||
* @param str |
||||
* @return |
||||
*/ |
||||
public static boolean isBase64(String str) { |
||||
if (str == null || str.trim().length() == 0) { |
||||
return false; |
||||
} |
||||
else { |
||||
if (str.length() % 4 != 0) { |
||||
return false; |
||||
} |
||||
|
||||
char[] strChars = str.toCharArray(); |
||||
|
||||
for (char c:strChars) { |
||||
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') |
||||
|| c == '+' || c == '/' || c == '=') { |
||||
continue; |
||||
} |
||||
else { |
||||
return false; |
||||
} |
||||
} |
||||
|
||||
return true; |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* des加密 |
||||
* @param datasource |
||||
* @param password |
||||
* @return |
||||
*/ |
||||
public static String desEncrypt(String datasource, String password) { |
||||
try { |
||||
SecureRandom random = new SecureRandom(); |
||||
DESKeySpec desKey = new DESKeySpec(password.getBytes()); |
||||
// 创建一个密匙工厂,然后用它把DESKeySpec转换成
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); |
||||
SecretKey securekey = keyFactory.generateSecret(desKey); |
||||
// Cipher对象实际完成加密操作
|
||||
Cipher cipher = Cipher.getInstance("DES"); |
||||
// 用密匙初始化Cipher对象
|
||||
cipher.init(Cipher.ENCRYPT_MODE, securekey, random); |
||||
// 现在,获取数据并加密
|
||||
// 正式执行加密操作
|
||||
return base64Encode(cipher.doFinal(datasource.getBytes())); |
||||
} catch (Throwable e) { |
||||
FRUtils.FRLogInfo("des 加密异常 " + e.getMessage()); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
|
||||
/** |
||||
* des 解密 |
||||
* @param src |
||||
* @param password |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static String desDecrypt(String src, String password) throws Exception { |
||||
// DES算法要求有一个可信任的随机数源
|
||||
SecureRandom random = new SecureRandom(); |
||||
// 创建一个DESKeySpec对象
|
||||
DESKeySpec desKey = new DESKeySpec(password.getBytes("UTF-8")); |
||||
// 创建一个密匙工厂
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); |
||||
// 将DESKeySpec对象转换成SecretKey对象
|
||||
SecretKey securekey = keyFactory.generateSecret(desKey); |
||||
// Cipher对象实际完成解密操作
|
||||
Cipher cipher = Cipher.getInstance("DES"); |
||||
// 用密匙初始化Cipher对象
|
||||
cipher.init(Cipher.DECRYPT_MODE, securekey, random); |
||||
// 真正开始解密操作
|
||||
return new String(cipher.doFinal(base64DecodeB(src))); |
||||
} |
||||
|
||||
/** |
||||
* 随机生成RSA密钥对 |
||||
* @throws NoSuchAlgorithmException |
||||
* @return privateKey,publicKey |
||||
*/ |
||||
public static Map<String,String> genRSAKeyPair() throws NoSuchAlgorithmException { |
||||
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
|
||||
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); |
||||
// 初始化密钥对生成器,密钥大小为96-1024位
|
||||
keyPairGen.initialize(1024,new SecureRandom()); |
||||
// 生成一个密钥对,保存在keyPair中
|
||||
KeyPair keyPair = keyPairGen.generateKeyPair(); |
||||
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
|
||||
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥
|
||||
String publicKeyString = base64Encode(publicKey.getEncoded()); |
||||
// 得到私钥字符串
|
||||
String privateKeyString = base64Encode(privateKey.getEncoded()); |
||||
// 将公钥和私钥保存到Map
|
||||
Map<String,String> result = new HashMap<String,String>(); |
||||
result.put("publicKey",publicKeyString.replaceAll("\n","").replace("\r","").trim()); |
||||
result.put("privateKey",privateKeyString.replaceAll("\n","").replace("\r","").trim()); |
||||
|
||||
return result; |
||||
} |
||||
|
||||
/** |
||||
* rsa 加密 |
||||
* @param str |
||||
* @param publicKey |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static String rsaEncrypt(String str,String publicKey) throws Exception { |
||||
//base64编码的公钥
|
||||
byte[] decoded = base64DecodeB(publicKey); |
||||
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); |
||||
//RSA加密
|
||||
Cipher cipher = Cipher.getInstance("RSA"); |
||||
cipher.init(Cipher.ENCRYPT_MODE, pubKey); |
||||
String outStr = base64Encode(cipher.doFinal(str.getBytes("UTF-8"))); |
||||
return outStr; |
||||
} |
||||
|
||||
/** |
||||
* rsa解密 |
||||
* @param str |
||||
* @param privateKey |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static String rsaDecrypt(String str,String privateKey) throws Exception { |
||||
//64位解码加密后的字符串
|
||||
byte[] inputByte = base64DecodeB(str); |
||||
//base64编码的私钥
|
||||
byte[] decoded = base64DecodeB(privateKey); |
||||
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); |
||||
//RSA解密
|
||||
Cipher cipher = Cipher.getInstance("RSA"); |
||||
cipher.init(Cipher.DECRYPT_MODE, priKey); |
||||
String outStr = new String(cipher.doFinal(inputByte)); |
||||
return outStr; |
||||
} |
||||
|
||||
} |
@ -0,0 +1,320 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import com.fr.base.ServerConfig; |
||||
import com.fr.base.TableData; |
||||
import com.fr.base.TemplateUtils; |
||||
import com.fr.decision.authority.AuthorityContext; |
||||
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType; |
||||
import com.fr.decision.authority.data.User; |
||||
import com.fr.decision.base.util.UUIDUtil; |
||||
import com.fr.decision.privilege.encrpt.PasswordValidator; |
||||
import com.fr.decision.webservice.bean.authentication.OriginUrlResponseBean; |
||||
import com.fr.decision.webservice.interceptor.handler.ReportTemplateRequestChecker; |
||||
import com.fr.decision.webservice.login.LogInOutResultInfo; |
||||
import com.fr.decision.webservice.utils.DecisionServiceConstants; |
||||
import com.fr.decision.webservice.utils.DecisionStatusService; |
||||
import com.fr.decision.webservice.utils.UserSourceFactory; |
||||
import com.fr.decision.webservice.v10.login.LoginService; |
||||
import com.fr.decision.webservice.v10.login.event.LogInOutEvent; |
||||
import com.fr.decision.webservice.v10.user.UserService; |
||||
import com.fr.event.EventDispatcher; |
||||
import com.fr.file.TableDataConfig; |
||||
import com.fr.general.data.DataModel; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.script.Calculator; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.stable.query.QueryFactory; |
||||
import com.fr.stable.query.restriction.RestrictionFactory; |
||||
import com.fr.third.springframework.web.method.HandlerMethod; |
||||
import com.fr.web.controller.ReportRequestService; |
||||
import com.fr.web.utils.WebUtils; |
||||
|
||||
import javax.servlet.http.Cookie; |
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import javax.servlet.http.HttpSession; |
||||
import java.io.IOException; |
||||
import java.util.List; |
||||
|
||||
public class FRUtils { |
||||
/** |
||||
* 判断用户是否存在 |
||||
* @param userName |
||||
* @return |
||||
*/ |
||||
public static boolean isUserExist(String userName){ |
||||
if (StringUtils.isEmpty(userName)) { |
||||
return false; |
||||
} else { |
||||
try { |
||||
List param1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName))); |
||||
return param1 != null && !param1.isEmpty(); |
||||
} catch (Exception param2) { |
||||
FineLoggerFactory.getLogger().error(param2.getMessage()); |
||||
return false; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 判断是否登录FR |
||||
* @param req |
||||
* @return |
||||
*/ |
||||
public static boolean isLogin(HttpServletRequest req){ |
||||
return LoginService.getInstance().isLogged(req); |
||||
} |
||||
|
||||
/** |
||||
* 帆软登录 |
||||
* @param httpServletRequest |
||||
* @param httpServletResponse |
||||
* @param userName |
||||
* @param url |
||||
*/ |
||||
public static void login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String userName,String url){ |
||||
|
||||
FineLoggerFactory.getLogger().info("FRLOG:用户名:"+userName); |
||||
FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url); |
||||
|
||||
|
||||
//判断用户名是否为空
|
||||
if(!Utils.isNullStr(userName)){ |
||||
if(isUserExist(userName)){ |
||||
String FRToken = ""; |
||||
|
||||
try { |
||||
//HttpSession session = httpServletRequest.getSession(true);
|
||||
|
||||
FRToken = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName); |
||||
|
||||
//httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,FRToken);
|
||||
|
||||
//session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, FRToken);
|
||||
EventDispatcher.fire(LogInOutEvent.LOGIN,new LogInOutResultInfo(httpServletRequest,httpServletResponse,userName,true)); |
||||
FineLoggerFactory.getLogger().info("FRLOG:登陆成功!"); |
||||
|
||||
if(!Utils.isNullStr(url)){ |
||||
httpServletResponse.sendRedirect(url); |
||||
} |
||||
} catch (Exception e) { |
||||
ResponseUtils.failedResponse(httpServletResponse,"登录异常,请联系管理员!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:登录异常,请联系管理员!"); |
||||
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); |
||||
} |
||||
}else{ |
||||
ResponseUtils.failedResponse(httpServletResponse,"用户在报表系统中不存在!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:用户在报表系统中不存在!"); |
||||
} |
||||
}else{ |
||||
ResponseUtils.failedResponse(httpServletResponse,"用户名不能为空!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:用户名不能为空!"); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 帆软登录 |
||||
* @param httpServletRequest |
||||
* @param httpServletResponse |
||||
* @param token |
||||
* @param url |
||||
*/ |
||||
public static void loginByToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String token,String url){ |
||||
|
||||
FineLoggerFactory.getLogger().info("FRLOG:token:"+token); |
||||
FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url); |
||||
|
||||
|
||||
//判断用户名是否为空
|
||||
if(!Utils.isNullStr(token)){ |
||||
writeToken2Cookie(httpServletResponse,token,-1); |
||||
|
||||
HttpSession session = httpServletRequest.getSession(true); |
||||
|
||||
httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token); |
||||
|
||||
session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token); |
||||
|
||||
if(!Utils.isNullStr(url)){ |
||||
try { |
||||
httpServletResponse.sendRedirect(url); |
||||
} catch (IOException e) { |
||||
ResponseUtils.failedResponse(httpServletResponse,"跳转异常!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:跳转异常!"); |
||||
} |
||||
} |
||||
}else{ |
||||
ResponseUtils.failedResponse(httpServletResponse,"token不能为空!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:token不能为空!"); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 获取token |
||||
* @param httpServletRequest |
||||
* @param httpServletResponse |
||||
* @param username |
||||
* @return |
||||
*/ |
||||
public static String getToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String username){ |
||||
String token = ""; |
||||
try { |
||||
token = LoginService.getInstance().login(httpServletRequest, httpServletResponse, username); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:获取token失败"+e.getMessage()); |
||||
} |
||||
|
||||
return token; |
||||
} |
||||
|
||||
private static void writeToken2Cookie(HttpServletResponse param1, String param2, int param3) { |
||||
try { |
||||
if (StringUtils.isNotEmpty(param2)) { |
||||
Cookie param4 = new Cookie("fine_auth_token", param2); |
||||
long param5 = param3 == -2 ? 1209600000L : (long)param3; |
||||
param4.setMaxAge((int)param5); |
||||
param4.setPath(ServerConfig.getInstance().getCookiePath()); |
||||
param1.addCookie(param4); |
||||
Cookie param7 = new Cookie("fine_remember_login", String.valueOf(param3 == -2 ? -2 : -1)); |
||||
param7.setMaxAge((int)param5); |
||||
param7.setPath(ServerConfig.getInstance().getCookiePath()); |
||||
param1.addCookie(param7); |
||||
} else { |
||||
FineLoggerFactory.getLogger().error("empty token cannot save."); |
||||
} |
||||
} catch (Exception param8) { |
||||
FineLoggerFactory.getLogger().error(param8.getMessage(), param8); |
||||
} |
||||
|
||||
} |
||||
|
||||
/** |
||||
* |
||||
* @param httpServletRequest |
||||
* @param httpServletResponse |
||||
*/ |
||||
public static void logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) |
||||
{ |
||||
if(!isLogin(httpServletRequest)){ |
||||
return ; |
||||
} |
||||
|
||||
try { |
||||
LoginService.getInstance().logout(httpServletRequest,httpServletResponse); |
||||
} catch (Exception e) { |
||||
ResponseUtils.failedResponse(httpServletResponse,"登出异常,请联系管理员!"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:登出异常,请联系管理员!"); |
||||
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage()); |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 打印FR日志 |
||||
* @param message |
||||
*/ |
||||
public static void FRLogInfo(String message){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:"+message); |
||||
} |
||||
|
||||
/** |
||||
* 打印FR日志-error |
||||
* @param message |
||||
*/ |
||||
public static void FRLogError(String message){ |
||||
FineLoggerFactory.getLogger().error("FRLOG:"+message); |
||||
} |
||||
|
||||
|
||||
/** |
||||
* 根据用户名获取用户信息 |
||||
* @param userName |
||||
* @return |
||||
*/ |
||||
public static User getFRUserByUserName(String userName){ |
||||
try { |
||||
return UserService.getInstance().getUserByUserName(userName); |
||||
} catch (Exception e) { |
||||
FRLogInfo("获取用户信息异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return null; |
||||
} |
||||
|
||||
/** |
||||
* 解密FR密码 |
||||
* @param password |
||||
* @return |
||||
*/ |
||||
// public static String decryptFRPsd(String password){
|
||||
// FRLogInfo("解密密码:"+password);
|
||||
// return TransmissionTool.decrypt(password);
|
||||
// }
|
||||
|
||||
/** |
||||
* 根据明文密码生成数据库中的密码,用户密码校验用 |
||||
* @return |
||||
*/ |
||||
public static String getDBPsd(String username,String password){ |
||||
PasswordValidator pv = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator(); |
||||
String uuid = UUIDUtil.generate(); |
||||
|
||||
return pv.encode(username, password, uuid); |
||||
} |
||||
|
||||
/** |
||||
* 获取带参数的访问链接 |
||||
* @return |
||||
*/ |
||||
public static String getAllUrl(HttpServletRequest httpServletRequest){ |
||||
return WebUtils.getOriginalURL(httpServletRequest); |
||||
} |
||||
|
||||
/** |
||||
* 根据originKey获取源链接 |
||||
* @param originKey |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static String getOriginUrl(String originKey) throws Exception { |
||||
if (StringUtils.isNotEmpty(originKey)) { |
||||
OriginUrlResponseBean originUrlResponseBean = (OriginUrlResponseBean) DecisionStatusService.originUrlStatusService().get(originKey); |
||||
DecisionStatusService.originUrlStatusService().delete(originKey); |
||||
if (originUrlResponseBean != null) { |
||||
return originUrlResponseBean.getOriginUrl(); |
||||
} |
||||
} |
||||
|
||||
return new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}")).getOriginUrl(); |
||||
} |
||||
|
||||
/** |
||||
* 判断是否开启模板认证 |
||||
* @param |
||||
* @return |
||||
* @throws Exception |
||||
*/ |
||||
public static boolean isTempAuth(HttpServletRequest req,HttpServletResponse res) throws Exception { |
||||
ReportTemplateRequestChecker checker = new ReportTemplateRequestChecker(); |
||||
HandlerMethod hm = new HandlerMethod(new ReportRequestService(),ReportRequestService.class.getMethod("preview", HttpServletRequest.class, HttpServletResponse.class, String.class)); |
||||
return checker.checkRequest(req,res,hm); |
||||
} |
||||
|
||||
/** |
||||
* 获取数据集数据 |
||||
* @param serverDataSetName |
||||
* @return |
||||
*/ |
||||
public static DataModel getTableData(String serverDataSetName){ |
||||
TableData userInfo = TableDataConfig.getInstance().getTableData(serverDataSetName); |
||||
DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator()); |
||||
// userInfoDM.getRowCount();
|
||||
// userInfoDM.getColumnIndex();
|
||||
// userInfoDM.getValueAt()
|
||||
return userInfoDM; |
||||
} |
||||
|
||||
public static String getIndex(HttpServletRequest req){ |
||||
String url = req.getScheme()+"://"+req.getServerName()+":"+String.valueOf(req.getServerPort())+req.getRequestURI(); |
||||
return url; |
||||
} |
||||
} |
@ -0,0 +1,265 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.third.org.apache.http.HttpEntity; |
||||
import com.fr.third.org.apache.http.HttpResponse; |
||||
import com.fr.third.org.apache.http.HttpStatus; |
||||
import com.fr.third.org.apache.http.NameValuePair; |
||||
import com.fr.third.org.apache.http.client.CookieStore; |
||||
import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity; |
||||
import com.fr.third.org.apache.http.client.methods.HttpGet; |
||||
import com.fr.third.org.apache.http.client.methods.HttpPost; |
||||
import com.fr.third.org.apache.http.conn.ssl.NoopHostnameVerifier; |
||||
import com.fr.third.org.apache.http.entity.StringEntity; |
||||
import com.fr.third.org.apache.http.impl.client.BasicCookieStore; |
||||
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.impl.cookie.BasicClientCookie; |
||||
import com.fr.third.org.apache.http.message.BasicNameValuePair; |
||||
import com.fr.third.org.apache.http.ssl.SSLContexts; |
||||
import com.fr.third.org.apache.http.ssl.TrustStrategy; |
||||
import com.fr.third.org.apache.http.util.EntityUtils; |
||||
|
||||
import javax.net.ssl.SSLContext; |
||||
import javax.servlet.http.Cookie; |
||||
import java.io.UnsupportedEncodingException; |
||||
import java.security.KeyManagementException; |
||||
import java.security.KeyStoreException; |
||||
import java.security.NoSuchAlgorithmException; |
||||
import java.security.cert.CertificateException; |
||||
import java.security.cert.X509Certificate; |
||||
import java.util.ArrayList; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.Set; |
||||
|
||||
public class HttpUtils { |
||||
|
||||
/** |
||||
* httpGet请求 |
||||
* @param url |
||||
* @return |
||||
*/ |
||||
public static String httpGet(String url,Cookie[] cookies,Map<String,String> header){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--url:"+url); |
||||
|
||||
//创建httpClient
|
||||
CloseableHttpClient httpclient = createHttpClient(cookies); |
||||
|
||||
HttpGet getMethod = new HttpGet(url); |
||||
|
||||
if(header != null && header.size() > 0){ |
||||
Set<String> keySet = header.keySet(); |
||||
|
||||
for(String key : keySet){ |
||||
getMethod.setHeader(key,header.get(key)); |
||||
} |
||||
} |
||||
|
||||
try { |
||||
HttpResponse response = httpclient.execute(getMethod); |
||||
int status =response.getStatusLine().getStatusCode(); |
||||
HttpEntity entity = response.getEntity(); |
||||
String returnResult = EntityUtils.toString(entity, "utf-8"); |
||||
|
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--status:"+status); |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--returnResult:"+returnResult); |
||||
|
||||
httpclient.close(); |
||||
|
||||
if (status == HttpStatus.SC_OK) { |
||||
return returnResult; |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--exception:"+e.getMessage()); |
||||
} |
||||
|
||||
try { |
||||
httpclient.close(); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return ""; |
||||
} |
||||
|
||||
/** |
||||
* HttpPost请求 |
||||
* @param postMethod |
||||
* @return |
||||
*/ |
||||
private static String HttpPost(HttpPost postMethod){ |
||||
CloseableHttpClient httpclient = createHttpClient(null); |
||||
|
||||
try { |
||||
HttpResponse response = httpclient.execute(postMethod); |
||||
int status = response.getStatusLine().getStatusCode(); |
||||
HttpEntity entity = response.getEntity(); |
||||
String returnResult = EntityUtils.toString(entity, "utf-8"); |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:status:"+status); |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:returnResult:"+returnResult); |
||||
httpclient.close(); |
||||
|
||||
if (status == HttpStatus.SC_OK) { |
||||
return returnResult; |
||||
} |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:exception:"+e.getMessage()); |
||||
} |
||||
|
||||
try { |
||||
httpclient.close(); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage()); |
||||
} |
||||
|
||||
return ""; |
||||
} |
||||
|
||||
public static String HttpPostXML(String url, String xmlParam){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:url:"+url); |
||||
|
||||
HttpPost postMethod = new HttpPost(url); |
||||
|
||||
postMethod.setHeader("Content-type", "text/html"); |
||||
HttpEntity entity2 = null; |
||||
try { |
||||
entity2 = new StringEntity(xmlParam); |
||||
} catch (UnsupportedEncodingException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:参数异常:"+e.getMessage()); |
||||
return ""; |
||||
} |
||||
|
||||
postMethod.setEntity(entity2); |
||||
|
||||
return HttpPost(postMethod); |
||||
} |
||||
|
||||
public static String HttpPostText(String url, String xmlParam){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostText:url:"+url); |
||||
|
||||
HttpPost postMethod = new HttpPost(url); |
||||
|
||||
postMethod.setHeader("Content-type", "text/plain"); |
||||
HttpEntity entity2 = null; |
||||
try { |
||||
entity2 = new StringEntity(xmlParam); |
||||
} catch (UnsupportedEncodingException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostText:参数异常:"+e.getMessage()); |
||||
return ""; |
||||
} |
||||
|
||||
postMethod.setEntity(entity2); |
||||
|
||||
return HttpPost(postMethod); |
||||
} |
||||
|
||||
public static String HttpPostJson(String url, String param,Map<String,String> header){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:url:"+url); |
||||
|
||||
HttpPost postMethod = new HttpPost(url); |
||||
|
||||
postMethod.setHeader("Content-Type","application/json"); |
||||
|
||||
if(header != null && header.size() > 0){ |
||||
Set<String> keySet = header.keySet(); |
||||
|
||||
for(String key : keySet){ |
||||
postMethod.setHeader(key,header.get(key)); |
||||
} |
||||
} |
||||
|
||||
if(!Utils.isNullStr(param)){ |
||||
HttpEntity entity2 = null; |
||||
try { |
||||
entity2 = new StringEntity(param); |
||||
} catch (UnsupportedEncodingException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:参数异常:"+e.getMessage()); |
||||
return ""; |
||||
} |
||||
|
||||
postMethod.setEntity(entity2); |
||||
} |
||||
|
||||
return HttpPost(postMethod); |
||||
} |
||||
|
||||
public static String HttpPostWWWForm(String url, Map<String,String> header,Map<String,String> param){ |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:url:"+url); |
||||
|
||||
HttpPost postMethod = new HttpPost(url); |
||||
|
||||
if(header != null && header.size() > 0){ |
||||
Set<String> keySet = header.keySet(); |
||||
|
||||
for(String key : keySet){ |
||||
postMethod.setHeader(key,header.get(key)); |
||||
} |
||||
} |
||||
|
||||
if(param != null && param.size() > 0){ |
||||
List<NameValuePair> params = new ArrayList<NameValuePair>(param.size()); |
||||
|
||||
for(Map.Entry<String,String> map : param.entrySet()){ |
||||
params.add(new BasicNameValuePair(map.getKey(), map.getValue())); |
||||
} |
||||
|
||||
try { |
||||
postMethod.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); |
||||
} catch (UnsupportedEncodingException e) { |
||||
FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:异常:"+e.getMessage()); |
||||
return ""; |
||||
} |
||||
} |
||||
|
||||
return HttpPost(postMethod); |
||||
} |
||||
|
||||
private static CloseableHttpClient createHttpClient(Cookie[] cookies){ |
||||
|
||||
SSLContext sslContext = null; |
||||
try { |
||||
sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { |
||||
@Override |
||||
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { |
||||
return true; |
||||
} |
||||
}).build(); |
||||
} catch (Exception e) { |
||||
FRUtils.FRLogInfo("exception:"+e.getMessage()); |
||||
} |
||||
|
||||
CloseableHttpClient httpclient = null; |
||||
|
||||
if(cookies != null && cookies.length > 0){ |
||||
CookieStore cookieStore = cookieToCookieStore(cookies); |
||||
|
||||
httpclient = HttpClients.custom().setSslcontext(sslContext). |
||||
setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultCookieStore(cookieStore).build(); |
||||
} |
||||
else{ |
||||
httpclient = HttpClients.custom().setSslcontext(sslContext). |
||||
setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); |
||||
} |
||||
|
||||
return httpclient; |
||||
} |
||||
|
||||
/** |
||||
* cookies转cookieStore |
||||
* @param cookies |
||||
* @return |
||||
*/ |
||||
public static CookieStore cookieToCookieStore(Cookie[] cookies){ |
||||
CookieStore cookieStore = new BasicCookieStore(); |
||||
|
||||
if(cookies != null && cookies.length>0){ |
||||
for(Cookie cookie : cookies){ |
||||
BasicClientCookie cookie1 = new BasicClientCookie(cookie.getName(), cookie.getValue()); |
||||
cookieStore.addCookie(cookie1); |
||||
} |
||||
} |
||||
|
||||
return cookieStore; |
||||
} |
||||
} |
@ -0,0 +1,26 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import io.jsonwebtoken.Claims; |
||||
import io.jsonwebtoken.Jwts; |
||||
|
||||
import javax.crypto.SecretKey; |
||||
import javax.crypto.spec.SecretKeySpec; |
||||
|
||||
public class JWTUtils { |
||||
|
||||
public static SecretKey generalKey(String secret) { |
||||
byte[] encodedKey = EncryptUtils.base64DecodeB(secret); |
||||
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); |
||||
return key; |
||||
} |
||||
|
||||
public static String parseJWT(String jwt, String secret){ |
||||
|
||||
SecretKey key = generalKey(secret); //签名秘钥,和生成的签名的秘钥一模一样
|
||||
|
||||
Claims claims = Jwts.parser().setSigningKey(key) //得到DefaultJwtParser
|
||||
.parseClaimsJws(jwt).getBody(); //设置需要解析的jwt
|
||||
return claims.getSubject(); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,108 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import com.fr.json.JSONObject; |
||||
import com.fr.log.FineLoggerFactory; |
||||
import com.fr.web.utils.WebUtils; |
||||
|
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import java.io.PrintWriter; |
||||
|
||||
public class ResponseUtils { |
||||
private static final int SUCCESS = 200; |
||||
private static final int FAILED = -1; |
||||
|
||||
public static void successResponse(HttpServletResponse res, String body) { |
||||
response(res, body, SUCCESS); |
||||
} |
||||
|
||||
public static void failedResponse(HttpServletResponse res, String body) { |
||||
response(res, body, FAILED); |
||||
} |
||||
|
||||
private static void response(HttpServletResponse res, String body, int code) { |
||||
JSONObject object = new JSONObject(); |
||||
PrintWriter pw; |
||||
try { |
||||
object.put("code", code); |
||||
object.put("data", body); |
||||
pw = WebUtils.createPrintWriter(res); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info(e.getMessage()); |
||||
return; |
||||
} |
||||
res.setContentType("application/json;charset=utf-8"); |
||||
String result = object.toString(); |
||||
pw.println(result); |
||||
pw.flush(); |
||||
pw.close(); |
||||
} |
||||
|
||||
public static void response(HttpServletResponse res,JSONObject json){ |
||||
PrintWriter pw; |
||||
try { |
||||
pw = WebUtils.createPrintWriter(res); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info(e.getMessage()); |
||||
return; |
||||
} |
||||
res.setContentType("application/json;charset=utf-8"); |
||||
String result = json.toString(); |
||||
pw.println(result); |
||||
pw.flush(); |
||||
pw.close(); |
||||
} |
||||
|
||||
public static void responseText(HttpServletResponse res,String text){ |
||||
PrintWriter pw; |
||||
try { |
||||
pw = WebUtils.createPrintWriter(res); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info(e.getMessage()); |
||||
return; |
||||
} |
||||
res.setContentType("text/html;charset=utf-8"); |
||||
pw.println(text); |
||||
pw.flush(); |
||||
pw.close(); |
||||
} |
||||
|
||||
public static void responseXml(HttpServletResponse res,String xml){ |
||||
PrintWriter pw; |
||||
try { |
||||
pw = WebUtils.createPrintWriter(res); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info(e.getMessage()); |
||||
return; |
||||
} |
||||
res.setContentType("text/xml;charset=utf-8"); |
||||
pw.println(xml); |
||||
pw.flush(); |
||||
pw.close(); |
||||
} |
||||
|
||||
public static void setCSRFHeader(HttpServletResponse httpServletResponse){ |
||||
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); |
||||
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH"); |
||||
httpServletResponse.setHeader("Access-Control-Max-Age", "36000"); |
||||
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization"); |
||||
} |
||||
|
||||
public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){ |
||||
PrintWriter pw; |
||||
try { |
||||
pw = WebUtils.createPrintWriter(res); |
||||
} catch (Exception e) { |
||||
FineLoggerFactory.getLogger().info(e.getMessage()); |
||||
return; |
||||
} |
||||
res.setContentType("text/javascript;charset=utf-8;charset=utf-8"); |
||||
String result = json.toString(); |
||||
|
||||
String jsonp=req.getParameter("callback"); |
||||
|
||||
pw.println(jsonp+"("+result+")"); |
||||
pw.flush(); |
||||
pw.close(); |
||||
} |
||||
} |
@ -0,0 +1,329 @@
|
||||
package com.eco.plugin.xx.addssso.utils; |
||||
|
||||
import com.fr.base.TemplateUtils; |
||||
import com.fr.data.NetworkHelper; |
||||
import com.fr.decision.webservice.v10.user.UserService; |
||||
import com.fr.io.utils.ResourceIOUtils; |
||||
import com.fr.json.JSONObject; |
||||
import com.fr.stable.CodeUtils; |
||||
import com.fr.stable.StringUtils; |
||||
import com.fr.third.org.apache.commons.codec.digest.DigestUtils; |
||||
import com.fr.web.utils.WebUtils; |
||||
|
||||
import javax.servlet.http.Cookie; |
||||
import javax.servlet.http.HttpServletRequest; |
||||
import javax.servlet.http.HttpServletResponse; |
||||
import java.io.BufferedReader; |
||||
import java.io.InputStream; |
||||
import java.net.URLEncoder; |
||||
import java.util.HashMap; |
||||
import java.util.List; |
||||
import java.util.Map; |
||||
import java.util.UUID; |
||||
import java.util.regex.Matcher; |
||||
import java.util.regex.Pattern; |
||||
|
||||
public class Utils { |
||||
|
||||
/** |
||||
* 判断字符串是否为空 |
||||
* @param str |
||||
* @return true 空字符串 false 非空字符串 |
||||
*/ |
||||
public static boolean isNullStr(String str){ |
||||
return !(str != null && !str.isEmpty() && !"null".equals(str)); |
||||
} |
||||
|
||||
/** |
||||
* 判断字符串是否非空 |
||||
* @param str |
||||
* @return |
||||
*/ |
||||
public static boolean isNotNullStr(String str){ |
||||
return !isNullStr(str); |
||||
} |
||||
|
||||
/** |
||||
* MD5加密 |
||||
* @param str |
||||
* @return |
||||
*/ |
||||
public static String getMd5Str(String str) |
||||
{ |
||||
return DigestUtils.md5Hex(str); |
||||
} |
||||
|
||||
/** |
||||
* 帆软shaEncode加密 |
||||
*/ |
||||
|
||||
public static String shaEncode(String str){ |
||||
return CodeUtils.sha256Encode(str); |
||||
} |
||||
|
||||
/** |
||||
* 获取uuid |
||||
*/ |
||||
public static String uuid(){ |
||||
return UUID.randomUUID().toString(); |
||||
} |
||||
|
||||
/** |
||||
* 替换空字符串 |
||||
* @param str |
||||
* @param replace |
||||
* @return |
||||
*/ |
||||
public static String replaceNullStr(String str,String replace){ |
||||
if(isNullStr(str)){ |
||||
return replace; |
||||
} |
||||
|
||||
return str; |
||||
} |
||||
|
||||
/** |
||||
* 获取请求体 |
||||
* @param req |
||||
* @return |
||||
*/ |
||||
public static JSONObject getRequestBody(HttpServletRequest req){ |
||||
StringBuffer sb = new StringBuffer(); |
||||
String line = null; |
||||
try { |
||||
BufferedReader reader = req.getReader(); |
||||
while ((line = reader.readLine()) != null) |
||||
sb.append(line); |
||||
} catch (Exception e) { |
||||
FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage()); |
||||
} |
||||
//将空格和换行符替换掉避免使用反序列化工具解析对象时失败
|
||||
String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n",""); |
||||
|
||||
JSONObject json = new JSONObject(jsonString); |
||||
|
||||
return json; |
||||
} |
||||
|
||||
/** |
||||
* 获取ip |
||||
* @return |
||||
*/ |
||||
public static String getIp(HttpServletRequest req){ |
||||
String realIp = req.getHeader("X-Real-IP"); |
||||
String fw = req.getHeader("X-Forwarded-For"); |
||||
if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) { |
||||
int param3 = fw.indexOf(","); |
||||
return param3 != -1 ? fw.substring(0, param3) : fw; |
||||
} else { |
||||
fw = realIp; |
||||
if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) { |
||||
return realIp; |
||||
} else { |
||||
if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) { |
||||
fw = req.getHeader("Proxy-Client-IP"); |
||||
} |
||||
|
||||
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { |
||||
fw = req.getHeader("WL-Proxy-Client-IP"); |
||||
} |
||||
|
||||
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { |
||||
fw = req.getHeader("HTTP_CLIENT_IP"); |
||||
} |
||||
|
||||
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { |
||||
fw = req.getHeader("HTTP_X_FORWARDED_FOR"); |
||||
} |
||||
|
||||
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) { |
||||
fw = req.getRemoteAddr(); |
||||
} |
||||
|
||||
return fw; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/** |
||||
* 根据key获取cookie |
||||
* @param req |
||||
* @return |
||||
*/ |
||||
public static String getCookieByKey(HttpServletRequest req,String key){ |
||||
Cookie[] cookies = req.getCookies(); |
||||
String cookie = ""; |
||||
|
||||
if(cookies == null || cookies.length <=0){ |
||||
return ""; |
||||
} |
||||
|
||||
for(int i = 0; i < cookies.length; i++) { |
||||
Cookie item = cookies[i]; |
||||
if (item.getName().equalsIgnoreCase(key)) { |
||||
cookie = item.getValue(); |
||||
} |
||||
} |
||||
|
||||
FRUtils.FRLogInfo("cookie:"+cookie); |
||||
|
||||
return cookie; |
||||
} |
||||
|
||||
/** |
||||
* 判断是否是手机端的链接 |
||||
* @param req |
||||
* @return |
||||
*/ |
||||
public static boolean isMobile(HttpServletRequest req) { |
||||
String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"}; |
||||
String userAgent = req.getHeader("user-agent"); |
||||
if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) { |
||||
for(String mobile : mobileArray) { |
||||
if(userAgent.toUpperCase().contains(mobile.toUpperCase())) { |
||||
return true; |
||||
} |
||||
} |
||||
} |
||||
return NetworkHelper.getDevice(req).isMobile(); |
||||
} |
||||
|
||||
/** |
||||
* 只编码中文 |
||||
* @param url |
||||
* @return |
||||
*/ |
||||
public static String encodeCH(String url ){ |
||||
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url); |
||||
|
||||
while(matcher.find()){ |
||||
String chn = matcher.group(); |
||||
url = url.replaceAll(chn, URLEncoder.encode(chn)); |
||||
} |
||||
|
||||
return url; |
||||
} |
||||
|
||||
/** |
||||
* 获取web-inf文件夹下的文件 |
||||
* filename /resources/ip4enc.properties |
||||
*/ |
||||
public static InputStream getResourcesFile(String filename){ |
||||
return ResourceIOUtils.read(filename); |
||||
} |
||||
|
||||
/** |
||||
* |
||||
* @param res |
||||
* @param path /com/fr/plugin/loginAuth/html/getMac.html |
||||
* @param parameterMap |
||||
*/ |
||||
public static void toErrorPage(HttpServletResponse res,String path,Map<String, String> parameterMap){ |
||||
if(parameterMap == null){ |
||||
parameterMap = new HashMap<String, String>(); |
||||
} |
||||
|
||||
try { |
||||
String macPage = TemplateUtils.renderTemplate(path, parameterMap); |
||||
WebUtils.printAsString(res, macPage); |
||||
}catch (Exception e){ |
||||
FRUtils.FRLogError("跳转页面异常"); |
||||
} |
||||
|
||||
} |
||||
|
||||
/** |
||||
* 判断是否是管理员 |
||||
* @param username |
||||
* @return |
||||
*/ |
||||
public static boolean isAdmin(String username) throws Exception{ |
||||
return UserService.getInstance().isAdmin(UserService.getInstance().getUserByUserName(username).getId()); |
||||
} |
||||
|
||||
/** |
||||
* 去掉浏览器中的参数 |
||||
* @param url |
||||
* @param param |
||||
* @return |
||||
*/ |
||||
public static String removeParam(String url,String param){ |
||||
if(!url.contains("?"+param) && !url.contains("&"+param)){ |
||||
return url; |
||||
} |
||||
|
||||
return url.substring(0,url.indexOf(url.contains("?"+param) ? "?"+param : "&"+param)); |
||||
} |
||||
|
||||
/** |
||||
* 获取跳转链接 |
||||
* @param req |
||||
* @param param |
||||
* @return |
||||
*/ |
||||
public static String getRedirectUrl(HttpServletRequest req,String param){ |
||||
String url = FRUtils.getAllUrl(req); |
||||
|
||||
if(isNotNullStr(param)){ |
||||
url = removeParam(url,param); |
||||
} |
||||
|
||||
url = encodeCH(url); |
||||
|
||||
return url; |
||||
} |
||||
|
||||
/** |
||||
* 去除空格换行 |
||||
* @param str |
||||
* @return |
||||
*/ |
||||
public static String trim(String str){ |
||||
return str.trim().replaceAll("\n","").replaceAll("\r",""); |
||||
} |
||||
|
||||
/** |
||||
* list 转化为指定字符分割的字符串 |
||||
* @param list |
||||
* @param list |
||||
* @return |
||||
*/ |
||||
public static String listToStr(List<String> list, String split){ |
||||
String result = ""; |
||||
|
||||
if(list == null || list.size() <= 0){ |
||||
return result; |
||||
} |
||||
|
||||
for(String str : list){ |
||||
result+=","+str; |
||||
} |
||||
|
||||
result = result.substring(1); |
||||
|
||||
return result; |
||||
} |
||||
|
||||
/** |
||||
* array 转化为指定字符分割的字符串 |
||||
* @param list |
||||
* @param list |
||||
* @return |
||||
*/ |
||||
public static String arrayToStr(String[] list, String split){ |
||||
String result = ""; |
||||
|
||||
if(list == null ||list.length <= 0){ |
||||
return result; |
||||
} |
||||
|
||||
for(int i=0;i<list.length;i++){ |
||||
String str = list[i]; |
||||
result+=","+str; |
||||
} |
||||
|
||||
result = result.substring(1); |
||||
|
||||
return result; |
||||
} |
||||
} |
@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html> |
||||
<html> |
||||
<head> |
||||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> |
||||
<title>error page</title> |
||||
</head> |
||||
<style> |
||||
.titlefont { |
||||
font-weight: bold; |
||||
font-size: large; |
||||
} |
||||
</style> |
||||
<body style=""> |
||||
<p class="titlefont">Failed to log in your account!</p> |
||||
<p class="titlefont">Please try:</p> |
||||
|
||||
<ul> |
||||
<li>Checking your network connection</li> |
||||
<li>Connecting to your Cisco VPN by the correct gateway</li> |
||||
<li>Closing the current page and reopen it</li> |
||||
<li>Contacting the DAP OPS team to register your account permissions</li> |
||||
</ul> |
||||
</body> |
||||
</html> |
Loading…
Reference in new issue