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 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 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 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"); } } }