Browse Source

open

master
pioneer 2 years ago
commit
2f06ec57a5
  1. 6
      README.md
  2. BIN
      lib/finekit-10.0-20191216.jar
  3. 31
      plugin.xml
  4. 143
      src/main/java/com/fr/plugin/oauth/LoginFilter.java
  5. 22
      src/main/java/com/fr/plugin/oauth/LoginOutComponent.java
  6. 70
      src/main/java/com/fr/plugin/oauth/LogoutFilter.java
  7. 38
      src/main/java/com/fr/plugin/oauth/MyFunction.java
  8. 73
      src/main/java/com/fr/plugin/oauth/W2Config.java
  9. 16
      src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java
  10. 157
      src/main/java/com/fr/plugin/oauth/http/OauthLoginHandler.java
  11. 38
      src/main/java/com/fr/plugin/oauth/http/OauthLogoutHandler.java
  12. 50
      src/main/java/com/fr/plugin/oauth/utils/CookieUtils.java
  13. 62
      src/main/java/com/fr/plugin/oauth/utils/GZipUtil.java
  14. 33
      src/main/java/com/fr/plugin/oauth/utils/HtmlUtils.java
  15. 199
      src/main/java/com/fr/plugin/oauth/utils/HttpUtils.java
  16. 52
      src/main/java/com/fr/plugin/oauth/utils/HttpsUtils.java
  17. 101
      src/main/java/com/fr/plugin/oauth/utils/RedirectUtils.java
  18. 61
      src/main/java/com/fr/plugin/oauth/utils/ResponseWrapper.java
  19. 12
      src/main/resources/com/fr/plugin/oauth/web/logout.js
  20. 11
      src/main/resources/com/fr/plugin/oauth/web/redirect.html
  21. 32
      src/main/resources/com/fr/plugin/oauth/web/redirectbyrole.html
  22. 18
      src/main/resources/com/fr/plugin/oauth/web/redirectcook.html

6
README.md

@ -0,0 +1,6 @@
# open-JSD-10117
JSD-10117 打开帆软登录页时重定向到客户统一认证平台登录页,输入账号密码登录后,会生成一个token,帆软解析token后获取用户名进行后台登录\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。

BIN
lib/finekit-10.0-20191216.jar

Binary file not shown.

31
plugin.xml

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<plugin>
<id>com.fr.plugin.JSD10117</id>
<name><![CDATA[单点登录]]></name>
<active>yes</active>
<version>1.10</version>
<env-version>10.0~11.0</env-version>
<jartime>2022-01-05</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[单点登录]]></description>
<function-recorder class="com.fr.plugin.oauth.LoginFilter"/>
<change-notes>
<![CDATA[
<p>[2022-5-7]项目启动</p>
]]>
</change-notes>
<main-package>com.fr.plugin.oauth</main-package>
<extra-decision>
<SystemOptionProvider class="com.fr.plugin.oauth.MyFunction"/>
<HttpHandlerProvider class="com.fr.plugin.oauth.http.HttpHandlerProvider"/>
<GlobalRequestFilterProvider class="com.fr.plugin.oauth.LoginFilter"/>
<GlobalRequestFilterProvider class="com.fr.plugin.oauth.LogoutFilter"/>
</extra-decision>
<extra-core>
</extra-core>
<extra-report>
</extra-report>
</plugin>

143
src/main/java/com/fr/plugin/oauth/LoginFilter.java

@ -0,0 +1,143 @@
package com.fr.plugin.oauth;
import com.fr.data.NetworkHelper;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.mobile.terminal.TerminalHandler;
import com.fr.decision.webservice.bean.authentication.LoginClientBean;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.login.TokenResource;
import com.fr.log.FineLoggerFactory;
import com.fr.plugin.oauth.utils.HtmlUtils;
import com.fr.plugin.oauth.utils.RedirectUtils;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.StringUtils;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
@FunctionRecorder
public class LoginFilter extends AbstractGlobalRequestFilterProvider {
private static final String REDIRECT_URI = "/plugin/public/com.fr.plugin.JSD10117/authLogin";
@Override
public void init(FilterConfig filterConfig) {
W2Config.getInstance();
super.init(filterConfig);
}
@Override
public String filterName() {
return "loginFilter";
}
@ExecuteFunctionRecord
@Override
public String[] urlPatterns() {
return new String[]{
/*"/decision/login",
"/login.html"*/
"/*"
};
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
boolean isLoginReq = isLoginReqest(req);
// 约定:放在iframe中的链接带参数iniframe=true
boolean iniframe = Boolean.parseBoolean(req.getParameter("iniframe"));
boolean sharetoken = Boolean.parseBoolean(req.getParameter("sharetoken"));
if (isLoginReq || iniframe || sharetoken) {
LoginClientBean bean = isLogined(req);
if (bean == null) {
boolean redirect = req.getMethod().equals("GET");
if (redirect) {
gotoAuthorize(req, res, iniframe, sharetoken);
return;
}
} else {
// 登录成功,跳转至目标页面
RedirectUtils.redirect(bean.getUsername(), W2Config.getInstance(), bean.getToken(), res);
return;
}
}
filterChain.doFilter(req, res);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
}
/**
* 跳转到统一登录页面
*/
public static void gotoAuthorize(HttpServletRequest req, HttpServletResponse res, boolean inIframe, boolean sharetoken) throws UnsupportedEncodingException {
W2Config w2Config = W2Config.getInstance();
String callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI, "UTF-8");
if (inIframe) {
callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI + "?iframeurl=" + getUrl(req), "UTF-8");
} else if (sharetoken) {
callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI + "?redirecturl=" + getUrl(req), "UTF-8");
}
callBack = callBack.replace("sharetoken", "nosharetoken");
callBack = callBack.replace("iniframe", "noiniframe");
String url = "";
if (sharetoken) {
url = callBack;
} else {
url = w2Config.getIdf() + callBack;
}
HtmlUtils.sendRedirect("", url, res);
}
private LoginClientBean isLogined(HttpServletRequest req) {
LoginClientBean bean = null;
try {
String token = TokenResource.COOKIE.getToken(req);
bean = LoginService.getInstance().loginStatusValid(token, TerminalHandler.getTerminal(req, NetworkHelper.getDevice(req)));
} catch (Exception e) {
bean = null;
FineLoggerFactory.getLogger().error(e.getMessage());
}
return bean;
}
private boolean isLoginReqest(HttpServletRequest req) {
String url = req.getRequestURL().toString();
if (StringUtils.isNotBlank(url)) {
if (url.endsWith("/decision/login") || url.endsWith("/login.html")) {
return true;
}
}
return false;
}
private static String getUrl(HttpServletRequest request) {
String url = request.getRequestURL().toString();
String param = request.getQueryString();
if (StringUtils.isNotBlank(param)) {
try {
if (request.getCharacterEncoding() != null) {
param = URLDecoder.decode(param, request.getCharacterEncoding());
}
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
url = url + "?" + param;
}
return url;
}
}

22
src/main/java/com/fr/plugin/oauth/LoginOutComponent.java

@ -0,0 +1,22 @@
package com.fr.plugin.oauth;
import com.fr.web.struct.Component;
import com.fr.web.struct.browser.RequestClient;
import com.fr.web.struct.category.ScriptPath;
import com.fr.web.struct.category.StylePath;
public class LoginOutComponent extends Component {
public static LoginOutComponent KEY = new LoginOutComponent();
@Override
public ScriptPath script(RequestClient requestClient) {
return ScriptPath.build("/com/fr/plugin/oauth/web/logout.js");
}
@Override
public StylePath style(RequestClient requestClient) {
return StylePath.EMPTY;
}
}

70
src/main/java/com/fr/plugin/oauth/LogoutFilter.java

@ -0,0 +1,70 @@
package com.fr.plugin.oauth;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.plugin.oauth.utils.CookieUtils;
import com.fr.plugin.oauth.utils.GZipUtil;
import com.fr.plugin.oauth.utils.ResponseWrapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_OK;
public class LogoutFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "logoutFilter";
}
@Override
public String[] urlPatterns() {
return new String[]{
"/decision/logout"
};
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
ResponseWrapper responseWrapper = new ResponseWrapper(res);
filterChain.doFilter(req, responseWrapper);
//String newContent = null;
String newContent = "{\"data\":\"https://xx/\"}";
byte[] content = responseWrapper.getContent();
if (content.length > 0 && res.getStatus() == SC_OK) {
String header = res.getHeader("Content-Encoding");
boolean isGzip = "gzip".equalsIgnoreCase(header);
if (isGzip) {
content = GZipUtil.decompress(content);
}
byte[] result = null;
if (isGzip) {
result = GZipUtil.compress(newContent.getBytes("UTF-8"));
res.setHeader("Content-Encoding", "gzip");
} else {
result = newContent.getBytes("UTF-8");
}
//把返回值输出到客户端
res.setContentLength(-1);
res.setContentType("text/html;charset=UTF-8");
ServletOutputStream out = res.getOutputStream();
out.write(result);
out.flush();
out.close();
res.flushBuffer();
}
Cookie cookie = CookieUtils.getLoginPathCookie(req);
CookieUtils.deleteCookie(res, cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
}

38
src/main/java/com/fr/plugin/oauth/MyFunction.java

@ -0,0 +1,38 @@
package com.fr.plugin.oauth;
import com.fr.decision.fun.impl.AbstractSystemOptionProvider;
import com.fr.decision.web.MainComponent;
import com.fr.plugin.transform.ExecuteFunctionRecord;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.web.struct.Atom;
public class MyFunction extends AbstractSystemOptionProvider {
public MyFunction() {
System.out.println("zc");
}
@Override
public String id() {
return "mb";
}
@Override
public String displayName() {
return "mb";
}
@Override
public int sortIndex() {
return 2;
}
@Override
public Atom attach() {
return MainComponent.KEY;
}
@Override
public Atom client() {
return LoginOutComponent.KEY;
}
}

73
src/main/java/com/fr/plugin/oauth/W2Config.java

@ -0,0 +1,73 @@
package com.fr.plugin.oauth;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
@Visualization(category = "统一认证单点配置")
public class W2Config extends DefaultConfiguration {
private static volatile W2Config config = null;
public static W2Config getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(W2Config.class);
}
return config;
}
/**
*
* 更改服务器后需要修改2个地方地址
* 1 这里
* 2 logout.js
* 3) 对应于验证服务器需要修改回调地址FANRUAN_HOST+frurl
*/
// product
private static final String FANRUAN_HOST = "http://xx/fineBi/webroot/";
@Identifier(value = "frurl", name = "当前报表域名", description = "", status = Status.SHOW)
private Conf<String> frurl = Holders.simple(FANRUAN_HOST + "decision");
@Identifier(value = "idf", name = "认证中心url", description = "", status = Status.SHOW)
private Conf<String> idf = Holders.simple("http://xx/lckj/pawm-uc/account_login.html?url=");
@Identifier(value = "userinfo", name = "获取用户信息", description = "", status = Status.SHOW)
private Conf<String> apiUserInfo = Holders.simple("http://xx/wmuc/loginServer/loginValidateToken");
public String getFrurl() {
return frurl.get();
}
public void setFrurl(String frurl) {
this.frurl.set(frurl);
}
public String getIdf() {
return idf.get();
}
public void setIdf(Conf<String> idf) {
this.idf = idf;
}
public String getApiUserInfo() {
return apiUserInfo.get();
}
public void setApiUserInfo(String apiUserInfo) {
this.apiUserInfo.set(apiUserInfo);
}
@Override
public Object clone() throws CloneNotSupportedException {
W2Config cloned = (W2Config) super.clone();
cloned.frurl = (Conf<String>) frurl.clone();
cloned.idf = (Conf<String>) idf.clone();
cloned.apiUserInfo = (Conf<String>) apiUserInfo.clone();
return cloned;
}
}

16
src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java

@ -0,0 +1,16 @@
package com.fr.plugin.oauth.http;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
public class HttpHandlerProvider extends AbstractHttpHandlerProvider {
HttpHandler[] actions = new HttpHandler[]{
new OauthLoginHandler(),
new OauthLogoutHandler()
};
@Override
public HttpHandler[] registerHandlers() {
return actions;
}
}

157
src/main/java/com/fr/plugin/oauth/http/OauthLoginHandler.java

@ -0,0 +1,157 @@
package com.fr.plugin.oauth.http;
import com.fanruan.api.json.JSONKit;
import com.finebi.constant.Constants;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.log.FineLoggerProvider;
import com.fr.plugin.oauth.LoginFilter;
import com.fr.plugin.oauth.W2Config;
import com.fr.plugin.oauth.utils.CookieUtils;
import com.fr.plugin.oauth.utils.HtmlUtils;
import com.fr.plugin.oauth.utils.HttpUtils;
import com.fr.plugin.oauth.utils.RedirectUtils;
import com.fr.stable.StringUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
public class OauthLoginHandler extends BaseHttpHandler {
FineLoggerProvider logger = FineLoggerFactory.getLogger();
@Override
public RequestMethod getMethod() {
return RequestMethod.GET;
}
@Override
public String getPath() {
return "/authLogin";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest req, HttpServletResponse resp) throws Exception {
W2Config w2Config = W2Config.getInstance();
String accessToken = req.getParameter("ssoTokenId");
if (StringUtils.isBlank(accessToken)) {
WebUtils.printAsString(resp, new String("未能获取token,登陆失败!".getBytes("gbk"), "utf-8"));
return;
}
String userName = getUserName(accessToken);
String token = login(req, resp, userName);
if (StringUtils.isBlank(token)) {
WebUtils.printAsString(resp, userName + new String("该用户没有本系统权限".getBytes("gbk"), "utf-8"));
return;
}
CookieUtils.setLoginCookie(resp);
String iframeUrl = req.getParameter("iframeurl");
String redirecturl = req.getParameter("redirecturl");
if (StringUtils.isNotBlank(iframeUrl)) {
// 跳转至报表链接
gotoFormLink(req, resp, iframeUrl);
} else if (StringUtils.isNotBlank(redirecturl)) {
HtmlUtils.sendRedirect(userName, redirecturl, token, resp, "/com/fr/plugin/oauth/web/redirectbyrole.html");
} else {
// 跳转至报表管理平台
RedirectUtils.redirect(userName, w2Config, token, resp);
}
//RedirectUtils.redirect(userName, w2Config, token, resp);
}
private String getUserName(String accessToken) {
//String url = String.format(API_GET_USERINFO, W2Config.getInstance().getIdf());
String url = String.format(W2Config.getInstance().getApiUserInfo(), W2Config.getInstance().getIdf());
Map<String, String> params = new HashMap<>();
params.put("tokenId", accessToken);
String json = null;
try {
//json = HttpKit.get(url, params);
json = HttpUtils.get(url, params);
logger.info("get user info response:" + json);
JSONObject jsonObject = JSONKit.create(json);
if (jsonObject != null && StringUtils.equals(jsonObject.getString("responseCode"), "000000")) {
JSONObject user = jsonObject.getJSONObject("data");
String um = user.getString("umAccount");
FineLoggerFactory.getLogger().info("have got user name :" + um);
if (StringUtils.isNotBlank(um)) {
return um.toUpperCase();
}
}
FineLoggerFactory.getLogger().info("have not got user name");
return "";
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
return "";
}
/**
* 后台登录方法
*/
private String login(HttpServletRequest req, HttpServletResponse res, String username) {
HttpSession session = req.getSession(true);
try {
return LoginService.getInstance().login(req, res, username);
// session.removeAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage(), e);
FineLoggerFactory.getLogger().error("login failed");
}
// session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
return "";
}
/**
* 跳转至报表链接
* 该链接放在iframe中为了写入cookie需要特殊处理
*/
private void gotoFormLink(HttpServletRequest req, HttpServletResponse resp, String url) {
boolean resetCookie = false;
String userAgent = req.getHeader("User-Agent");
if (StringUtils.isNotBlank(userAgent) && userAgent.contains("Chrome")) {
resetCookie = true;
}
Collection<String> collection = resp.getHeaders("Set-Cookie");
if (collection != null && collection.size() > 0) {
HashMap hashMap = new HashMap();
String cookies = "";
if (resetCookie) {
for (String c : collection) {
cookies = cookies + c + ";Secure;SameSite=None;@@";
}
}
hashMap.put("cookies", cookies);
hashMap.put("callBack", url);
try {
WebUtils.writeOutTemplate("/com/fr/plugin/oauth/web/redirectcook.html", resp, hashMap);
} catch (IOException e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
} else {
FineLoggerFactory.getLogger().error("login failed, there must be cookies");
}
}
}

38
src/main/java/com/fr/plugin/oauth/http/OauthLogoutHandler.java

@ -0,0 +1,38 @@
package com.fr.plugin.oauth.http;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.plugin.oauth.W2Config;
import com.fr.plugin.oauth.utils.HtmlUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 这个类可能用不上暂时留着看
*/
public class OauthLogoutHandler extends BaseHttpHandler {
// 这个接口会导致竹云所有账号都退出
private static final String API_GLO = "%s/idp/profile/OAUTH2/Redirect/GLO?redirctToUrl=%s&redirectToLogin=true&entityId=%s";
@Override
public RequestMethod getMethod() {
return RequestMethod.GET;
}
@Override
public String getPath() {
return "/authLogout";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
}
}

50
src/main/java/com/fr/plugin/oauth/utils/CookieUtils.java

@ -0,0 +1,50 @@
package com.fr.plugin.oauth.utils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieUtils {
public static final String COOKIE_LOGINPATH_NAME = "loginpath";
public static final String COOKIE_LOGINPATH_VALUE = "sso";
public static void setLoginCookie(HttpServletResponse res) {
Cookie cookie = new Cookie(COOKIE_LOGINPATH_NAME, COOKIE_LOGINPATH_VALUE);
cookie.setPath("/");
res.addCookie(cookie);
}
public static boolean isLoginFromSSO(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (COOKIE_LOGINPATH_NAME.equals(cookie.getName())) {
if (COOKIE_LOGINPATH_VALUE.equals(cookie.getValue())) {
return true;
}
}
}
return false;
}
public static Cookie getCookie(HttpServletRequest req, String name) {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public static Cookie getLoginPathCookie(HttpServletRequest req) {
return getCookie(req, COOKIE_LOGINPATH_NAME);
}
public static void deleteCookie(HttpServletResponse res, Cookie cookie) {
if (cookie != null){
cookie.setMaxAge(0);
res.addCookie(cookie);
}
}
}

62
src/main/java/com/fr/plugin/oauth/utils/GZipUtil.java

@ -0,0 +1,62 @@
package com.fr.plugin.oauth.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipUtil {
public static final int BUFFER = 1024;
/**
* 数据压缩
*/
public static void compress(InputStream is, OutputStream os) throws Exception {
GZIPOutputStream gos = new GZIPOutputStream(os);
int count;
byte data[] = new byte[BUFFER];
while ((count = is.read(data, 0, BUFFER)) != -1) {
gos.write(data, 0, count);
}
gos.finish();
gos.flush();
gos.close();
}
public static byte[] compress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
compress(bais, baos);
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
/**
* 数据解压
*/
public static void decompress(InputStream is, OutputStream os) throws Exception {
GZIPInputStream gis = new GZIPInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}
gis.close();
}
public static byte[] decompress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
decompress(bais, baos);
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
}

33
src/main/java/com/fr/plugin/oauth/utils/HtmlUtils.java

@ -0,0 +1,33 @@
package com.fr.plugin.oauth.utils;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
public class HtmlUtils {
public static void sendRedirect(String userName,String url, HttpServletResponse httpServletResponse) {
HashMap hashMap = new HashMap();
hashMap.put("loginUser", userName);
hashMap.put("callBack", url);
try {
WebUtils.writeOutTemplate("/com/fr/plugin/oauth/web/redirect.html", httpServletResponse, hashMap);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendRedirect(String userName,String url, String token, HttpServletResponse httpServletResponse, String html) {
HashMap hashMap = new HashMap();
hashMap.put("loginUser", userName);
hashMap.put("callBack", url);
hashMap.put("accessToken", token);
try {
WebUtils.writeOutTemplate(html, httpServletResponse, hashMap);
} catch (IOException e) {
e.printStackTrace();
}
}
}

199
src/main/java/com/fr/plugin/oauth/utils/HttpUtils.java

@ -0,0 +1,199 @@
package com.fr.plugin.oauth.utils;
import com.fr.base.ServerConfig;
import com.fr.json.JSONObject;
import com.fr.third.fasterxml.jackson.core.JsonParseException;
import com.fr.third.fasterxml.jackson.databind.DeserializationFeature;
import com.fr.third.fasterxml.jackson.databind.JsonMappingException;
import com.fr.third.fasterxml.jackson.databind.ObjectMapper;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HttpUtils {
private static ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public static String getRequestPayload(HttpServletRequest req) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = req.getReader();) {
char[] buff = new char[1024];
int len;
while ((len = reader.read(buff)) != -1) {
sb.append(buff, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
public static <T> T json2Object(String json, Class<T> typeRef) {
try {
return (T) mapper.readValue(json, typeRef);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
}
return null;
}
public static String object2Json(Object ok) {
try {
return mapper.writeValueAsString(ok);
} catch (JsonParseException e) {
} catch (JsonMappingException e) {
} catch (IOException e) {
}
return "";
}
public JSONObject createResp(String uid, String reqId) {
JSONObject json = new JSONObject();
json.put("uid", uid);
json.put("bimRequestId", reqId);
json.put("resultCode", "0");
json.put("message", "success");
return json;
}
private static String getParam(Map<String, String> var0, String enc) {
String var1 = "";
Set var2 = var0.keySet();
Iterator var3 = var2.iterator();
while (var3.hasNext()) {
String var4 = (String) var3.next();
String var5 = var0.get(var4) + "";
try {
var1 = var1 + (var1.length() == 0 ? "" : "&") + URLEncoder.encode(var4, enc) + "=" + URLEncoder.encode(var5, enc);
} catch (Exception var7) {
;
}
}
return var1;
}
public static boolean isHttps(URL url) {
return url.getProtocol().toLowerCase().equals("https");
}
public static String get(String path, Map<String, String> param) {
String paramStr = getParam(param, ServerConfig.getInstance().getServerCharset());
BufferedReader input = null;
StringBuilder sb = null;
URL url = null;
HttpURLConnection con = null;
try {
url = new URL(path + (paramStr.length() > 0 ? "?" + paramStr.toString() : ""));
if (isHttps(url)) {
HttpsUtils.trustAllHosts();
HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection();
httpsCon.setHostnameVerifier(HttpsUtils.DO_NOT_VERIFY);
con = httpsCon;
} else {
con = (HttpURLConnection) url.openConnection();
}
con.setRequestProperty("accept", "*/*");
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Charset", "UTF-8");
input = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
sb = new StringBuilder();
String s;
while ((s = input.readLine()) != null) {
sb.append(s).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// close buffered
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// disconnecting releases the timescroller held by a connection so they may be closed or reused
if (con != null) {
con.disconnect();
}
}
return sb == null ? null : sb.toString();
}
public static String post(String path, Map<String, String> param) {
String paramStr = getParam(param, ServerConfig.getInstance().getServerCharset());
PrintWriter writer = null;
BufferedReader reader = null;
HttpURLConnection con = null;
String result = "";
try {
URL url = new URL(path);
if (isHttps(url)) {
HttpsUtils.trustAllHosts();
HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection();
httpsCon.setHostnameVerifier(HttpsUtils.DO_NOT_VERIFY);
con = httpsCon;
} else {
con = (HttpURLConnection) url.openConnection();
}
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
//con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// var8.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
writer = new PrintWriter(con.getOutputStream());
writer.print(paramStr);
writer.flush();
String line;
for (reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); (line = reader.readLine()) != null; result = result + line) {
;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
} catch (Exception var17) {
;
}
}
return result;
}
}

52
src/main/java/com/fr/plugin/oauth/utils/HttpsUtils.java

@ -0,0 +1,52 @@
package com.fr.plugin.oauth.utils;
import com.fr.log.FineLoggerFactory;
import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class HttpsUtils {
final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Create a trust manager that does not validate certificate chains
static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
FineLoggerFactory.getLogger().error("checkClientTrusted");
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
FineLoggerFactory.getLogger().error("checkServerTrusted");
}
}};
static SSLContext sc;
static {
trustAllHosts();
}
/**
* Trust every server - dont check for any certificate
*/
public static void trustAllHosts() {
// Install the all-trusting trust manager
try {
if (sc == null) {
sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
}
}

101
src/main/java/com/fr/plugin/oauth/utils/RedirectUtils.java

@ -0,0 +1,101 @@
package com.fr.plugin.oauth.utils;
import com.fr.io.utils.ResourceIOUtils;
import com.fr.plugin.oauth.W2Config;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class RedirectUtils {
public static String ORACLE;
public static String USER_NAME;
public static String PASSWORD;
public static Properties getProperties() throws IOException {
InputStream is = ResourceIOUtils.read("/resources/oauth2095.properties");
Properties prop = new Properties();
prop.load(is);
ORACLE = prop.getProperty("oracle", "jdbc:oracle:thin:@1xx:xx:xx");
USER_NAME = prop.getProperty("username", "xx");
PASSWORD = prop.getProperty("password", "xx");
return prop;
}
/**
* 登录成功跳转至目标页面
*/
public static void redirect(String userName, W2Config config, String token, HttpServletResponse resp) throws IOException {
String url = config.getFrurl();
HtmlUtils.sendRedirect(userName, url, token, resp, "/com/fr/plugin/oauth/web/redirectbyrole.html");
}
private static String getRole(String userName) {
String role = "";
Connection con = null;
PreparedStatement pre = null;
ResultSet result = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String _result = ORACLE;
String us = USER_NAME;
String pw = PASSWORD;
con = DriverManager.getConnection(_result, us, pw);
String sql = "SELECT ORG_LEVEL FROM HR_MANAGEMENT WHERE USERNAME = ?";
pre = con.prepareStatement(sql);
pre.setString(1, userName);
result = pre.executeQuery();
if (result.next()) {
role = result.getString("ORG_LEVEL");
}
} catch (Exception e) {
e.printStackTrace();
try {
if (result != null) {
result.close();
}
if (pre != null) {
pre.close();
}
if (con != null) {
con.close();
}
} catch (Exception var19) {
var19.printStackTrace();
}
} finally {
try {
if (result != null) {
result.close();
}
if (pre != null) {
pre.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return role;
}
}

61
src/main/java/com/fr/plugin/oauth/utils/ResponseWrapper.java

@ -0,0 +1,61 @@
package com.fr.plugin.oauth.utils;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream buffer;
private ServletOutputStream out;
public ResponseWrapper(HttpServletResponse httpServletResponse) {
super(httpServletResponse);
buffer = new ByteArrayOutputStream();
out = new WrapperOutputStream(buffer);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return out;
}
@Override
public void flushBuffer() throws IOException {
if (out != null) {
out.flush();
}
}
public byte[] getContent() throws IOException {
flushBuffer();
return buffer.toByteArray();
}
class WrapperOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bos;
public WrapperOutputStream(ByteArrayOutputStream bos) {
this.bos = bos;
}
@Override
public void write(int b) throws IOException {
bos.write(b);
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener arg0) {
}
}
}

12
src/main/resources/com/fr/plugin/oauth/web/logout.js

@ -0,0 +1,12 @@
;(function () {
Dec.Logout = function() {
Dec.Utils.logout(function(e) {
BI.Cache.deleteCookie(DecCst.Cookie.TOKEN, Dec.system.cookiePath);
setTimeout(function () {
window.location.href = "http://xx/fineBi/webroot/decision";
},300);
})
}
})();

11
src/main/resources/com/fr/plugin/oauth/web/redirect.html

@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
window.location.href = '${callBack}';
</script>
</head>
<body>
<!--<h3>登陆成功${loginUser},5秒后跳转到:${callBack}</h3>-->
</body>
</html>

32
src/main/resources/com/fr/plugin/oauth/web/redirectbyrole.html

@ -0,0 +1,32 @@
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function addCookie (name, value, path, expiresHours) {
var cookieString = name + "=" + escape(value);
if (expiresHours && expiresHours > 0) {
var date = new Date();
date.setTime(BI.getTime() + expiresHours * 3600 * 1000);
cookieString = cookieString + "; expires=" + date.toGMTString();
}
if (path) {
cookieString = cookieString + "; path=" + path;
}
document.cookie = cookieString;
}
function is_iPad(){
var screenHeight = document.documentElement.clientHeight;//获取可见区域的高度;
var screenWidth = document.documentElement.clientWidth;//获取可见区域的宽度;
console.info('screenClient Width Height:',screenHeight,screenWidth);
return screenWidth < 1400 && screenHeight < 1000;
}
addCookie("fine_auth_token", `${accessToken}`, "/", -1);
window.location.href = `${callBack}`;
</script>
</head>
<body>
<!--<h3>登陆成功${loginUser},5秒后跳转到:${callBack}</h3>-->
</body>
</html>

18
src/main/resources/com/fr/plugin/oauth/web/redirectcook.html

@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
var cookstr = `${cookies}`;
var cookarr = cookstr.split('@@');
for (var i = 0; i < cookarr.length; i++) {
document.cookie = cookarr[i];
}
console.log("cook doc is "+ document.cookie);
window.location.href = `${callBack}`;
</script>
</head>
<body>
<!--<h3>登陆成功${loginUser},5秒后跳转到:${callBack}</h3>-->
</body>
</html>
Loading…
Cancel
Save