Browse Source

open

master
pioneer 1 year ago
commit
66f645837d
  1. 6
      README.md
  2. BIN
      lib/finekit-10.0-20191216.jar
  3. 31
      plugin.xml
  4. 138
      src/main/java/com/fr/plugin/oauth/LoginFilter.java
  5. 21
      src/main/java/com/fr/plugin/oauth/LoginOutComponent.java
  6. 69
      src/main/java/com/fr/plugin/oauth/LogoutFilter.java
  7. 38
      src/main/java/com/fr/plugin/oauth/MyFunction.java
  8. 95
      src/main/java/com/fr/plugin/oauth/W2Config.java
  9. 16
      src/main/java/com/fr/plugin/oauth/http/HttpHandlerProvider.java
  10. 174
      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. 16
      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-10053
JSD-10053 竹云单点登录\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【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.xx</id>
<name><![CDATA[单点登录]]></name>
<active>yes</active>
<version>1.09</version>
<env-version>10.0</env-version>
<jartime>2020-03-10</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[单点登录]]></description>
<function-recorder class="com.fr.plugin.oauth.LoginFilter"/>
<change-notes>
<![CDATA[
<p>[2022-4-20]项目启动</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>

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

@ -0,0 +1,138 @@
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.io.utils.ResourceIOUtils;
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 com.fr.web.utils.WebUtils;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;
@FunctionRecorder
public class LoginFilter extends AbstractGlobalRequestFilterProvider {
private static final String API_AUTHORIZE = "%s/idp/authCenter/authenticate?redirect_uri=%s&client_id=%s&response_type=code&state=123";
private static final String REDIRECT_URI = "/plugin/public/com.fr.plugin.xx/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",
"/decision/view/form"
};
}
private static final String ADMIN = "admin";
private static final String VIEWLET_DIRECT = "B2B/sell_in";
private static final String VIEWLET_DIRECT2 = "B2B%2Fsell_in";
private static final String VIEWLET_DIRECT3 = "B2B%252Fsell_in";
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
try {
LoginClientBean bean = isLogined(req);
boolean isForm = req.getRequestURI().endsWith("view/form");
if (bean == null) {
boolean redirect = false;
if (isForm) {
String viewlet = req.getParameter("viewlet");
redirect = StringUtils.isNotBlank(viewlet) ?
(viewlet.startsWith(VIEWLET_DIRECT) || viewlet.startsWith(VIEWLET_DIRECT2) || viewlet.startsWith(VIEWLET_DIRECT3)) : false;
} else {
String queryString = req.getQueryString();
boolean isAdmin = StringUtils.isNotBlank(queryString) ? ADMIN.equalsIgnoreCase(queryString) : false;
redirect = req.getMethod().equals("GET") && !isAdmin;
}
if (redirect) {
getAuthorizeCode(req, res, isForm);
return;
}
} else if (!isForm) {
// 登录成功,跳转至报表管理平台
RedirectUtils.redirect(bean.getUsername(), W2Config.getInstance(), bean.getToken(), res);
return;
}
/*res.setHeader("Content-type", "text/html;charset=UTF-8");
res.setCharacterEncoding("UTF-8");
res.getWriter().write("该账号已经登录!");*/
filterChain.doFilter(req, res);
} catch (Exception e) {
FineLoggerFactory.getLogger().error(e.getMessage());
}
}
public static void getAuthorizeCode(HttpServletRequest req, HttpServletResponse res, boolean isForm) throws UnsupportedEncodingException {
W2Config w2Config = W2Config.getInstance();
String callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI, "UTF-8");
if (isForm) {
callBack = URLEncoder.encode(w2Config.getFrurl() + REDIRECT_URI + "?form=" + getUrl(req), "UTF-8");
}
String url = String.format(API_AUTHORIZE, w2Config.getIdf(), callBack, w2Config.getOwclientId());
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 var4) {
bean = null;
}
return bean;
}
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;
}
}

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

@ -0,0 +1,21 @@
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;
}
}

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

@ -0,0 +1,69 @@
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;
}
}

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

@ -0,0 +1,95 @@
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
*/
private static final String FANRUAN_HOST = "https://xx/";
@Identifier(value = "frlogin", name = "登录域名", description = "", status = Status.SHOW)
//private Conf<String> frlogin = Holders.simple(FANRUAN_HOST + "login.html");
private Conf<String> frlogin = Holders.simple(FANRUAN_HOST + "SSOlogin.html");
@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("https://xx");
@Identifier(value = "owclientId", name = "OauthClientId", description = "", status = Status.SHOW)
private Conf<String> owclientId = Holders.simple("xx");
@Identifier(value = "owclientSecret", name = "client_secret", description = "", status = Status.SHOW)
private Conf<String> owclientSecret = Holders.simple("xx");
public Conf<String> getFrlogin() {
return frlogin;
}
public void setFrlogin(Conf<String> frlogin) {
this.frlogin = frlogin;
}
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 getOwclientId() {
return owclientId.get();
}
public void setOwclientId(String clientId) {
this.owclientId.set(clientId);
}
public String getOwclientSecret() {
return owclientSecret.get();
}
public void setOwclientSecret(String owclientSecret) {
this.owclientSecret.set(owclientSecret);
}
@Override
public Object clone() throws CloneNotSupportedException {
W2Config cloned = (W2Config) super.clone();
cloned.frurl = (Conf<String>) frurl.clone();
cloned.owclientId = (Conf<String>) owclientId.clone();
cloned.owclientSecret = (Conf<String>) owclientSecret.clone();
cloned.idf = (Conf<String>) idf.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;
}
}

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

@ -0,0 +1,174 @@
package com.fr.plugin.oauth.http;
import com.fanruan.api.json.JSONKit;
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.Cookie;
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();
private static final String API_GET_TOKEN = "%s:8083/xx/oauth2/getToken?client_id=%s&grant_type=authorization_code&code=%s&client_secret=%s";
private static final String API_GET_USERINFO = "%s:8083/xxx/oauth2/getUserInfo";
@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 code = req.getParameter("code");
if (StringUtils.isBlank(code)) {
WebUtils.printAsString(resp, "can't get code from zuyun!");
return;
/*LoginFilter.getAuthorizeCode(resp);
return;*/
}
String url4GetToken = String.format(API_GET_TOKEN, w2Config.getIdf(), w2Config.getOwclientId(), code, w2Config.getOwclientSecret());
Map<String, String> params = new HashMap<>();
String json = HttpUtils.post(url4GetToken, params);
if (StringUtils.isEmpty(json)) {
logger.error("第一次获取token返回空,再次请求!");
json = HttpUtils.post(url4GetToken, params);
}
logger.debug("gettoken is " + json);
JSONObject jsonObject = JSONKit.create(json);
if (jsonObject.has("errcode")) {
WebUtils.printAsString(resp, "登陆失败:" + jsonObject.getString("errcode") + " 描述:" + jsonObject.getString("msg"));
return;
}
String access_token = jsonObject.getString("access_token");
logger.debug("当前登陆获取的accessToken" + access_token);
String userName = getUserName(access_token);
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 formUrl = req.getParameter("form");
if (StringUtils.isNotBlank(formUrl)) {
// 跳转至报表链接
gotoFormLink(req, resp, formUrl);
//HtmlUtils.sendRedirect(userName, formUrl, token, resp, "/com/fr/plugin/oauth/web/redirectbyrole.html");
} else {
// 跳转至报表管理平台
RedirectUtils.redirect(userName, w2Config, token, resp);
}
}
private String getUserName(String accessToken) {
String url = String.format(API_GET_USERINFO, W2Config.getInstance().getIdf());
Map<String, String> params = new HashMap<>();
params.put("client_id", W2Config.getInstance().getOwclientId());
params.put("access_token", accessToken);
String json = null;
try {
//json = HttpKit.get(url, params);
json = HttpUtils.get(url, params);
logger.error("当前登陆响应" + json);
JSONObject jsonObject = JSONKit.create(json);
/*String uid = jsonObject.getString("uid");
String displayName = jsonObject.getString("displayName");
String loginName = jsonObject.getString("loginName");*/
String roles = jsonObject.getString("spRoleList");
JSONArray jsonArray = JSONKit.createJSONArray(roles);
List roleList = jsonArray.getList();
Object o = roleList.get(0);
return String.valueOf(o);
} 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:@xx:xx:xx");
USER_NAME = prop.getProperty("username", "xxx");
PASSWORD = prop.getProperty("password", "xxx");
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) {
}
}
}

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

@ -0,0 +1,16 @@
;(function () {
Dec.Logout = function() {
Dec.Utils.logout(function(e) {
BI.Cache.deleteCookie(DecCst.Cookie.TOKEN, Dec.system.cookiePath);
setTimeout(function () {
//var flag = BI.Cache.getCookie("loginpath");
window.location.href = "https://exxxx";
/*if (flag == "sso") {
window.location.href = "http://xxxx/SSOlogin.html";
} else {
window.location.href = "http://xxxx/login.html";
}*/
},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