E10自定义统一认证+人员同步
需求背景:用户希望三方系统首次单点OA的时候,实现人员同步及认证登录,后续同步过的人员可直接登录。
需求分析:三方系统人数很多,全部同步到OA授权不够,而且不是所有人员都用OA,所以才会有这样的需求。
开发方案:实现E10自定义统一认证类接口,在三方提供的OAuth2的接口中获取到当前单点人员信息,查询是否已存在OA中并且状态正常,存在直接返回登录成功标识与人员信息;存在但人员已离职,返回登录失败信息;不存在,则通过 openapi 人员同步接口同步人员信息,最后返回登录成功标识与人员信息。
其他要点:因为开发环境与生产环境的秘钥各种信息可能会不一致,最好支持可配置,该用户采用单体部署的E10,该开发中还涉及配置文件部分处理。
E9OAuth2CustomZWH 自定义统一认证核心类
package com.weaver.intunifyauth.client.custom.service.impl.xxx;import com.alibaba.fastjson.JSONObject;
import com.weaver.ebuilder.datasource.api.entity.SqlParamEntity;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.enums.SqlParamType;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.intunifyauth.client.custom.service.AuthclientCustomService;
import com.weaver.intunifyauth.client.custom.service.impl.xxx.constant.OAuth2CustomProperty;
import com.weaver.intunifyauth.client.custom.service.impl.xxx.util.DbHelper;
import com.weaver.intunifyauth.client.custom.service.impl.xxx.util.HttpsUtil;
import com.weaver.intunifyauth.client.custom.service.impl.xxx.util.SpringContextUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import static com.weaver.intunifyauth.client.custom.service.impl.xxx.util.CommonUtil.syncUserInfo;@Component
public class E9OAuth2CustomZWH implements AuthclientCustomService {private static final Logger LOGGER = LoggerFactory.getLogger(E9OAuth2CustomZWH.class);@Autowiredprivate DbHelper dbHelper;private final OAuth2CustomProperty prop = SpringContextUtil.getBean(OAuth2CustomProperty.class);@SneakyThrows@Overridepublic Map<String, String> login(HttpServletRequest request, HttpServletResponse response) {LOGGER.error("E9OAuth2CustomZWH login 登录接口自定义实现 Start");Map<String, String> reMap = new HashMap<>();String ssoAddressCode = prop.getSSO_ADDRESS_CODE();String clintIdKey = prop.getCLINT_ID_KEY();String clintIdValue = prop.getCLINT_ID_VALUE();String stateKey = prop.getSTATE_KEY();String stateValue = prop.getSTATE_VALUE();String redirectUriKey = prop.getREDIRECT_URI_KEY();String redirectUriValue = prop.getREDIRECT_URI_VALUE();LOGGER.error("SSO Address Code: {}, Client ID Key: {}, Client ID Value: {}, State Key: {}, State Value: {}, Redirect URI Key: {}, Redirect URI Value: {}",ssoAddressCode, clintIdKey, clintIdValue, stateKey, stateValue, redirectUriKey, redirectUriValue);String redirectUrl = ssoAddressCode + "/login/oauth/authorize?" +clintIdKey + "=" + clintIdValue + "&" +stateKey + "=" + stateValue + "&" +redirectUriKey + "=" + URLEncoder.encode(redirectUriValue, "UTF-8");LOGGER.error("redirectUrl ---> " + redirectUrl);reMap.put("redirectUrl", redirectUrl);return reMap;}@SneakyThrows@Overridepublic Map<String, String> getUserInfo(HttpServletRequest request, HttpServletResponse response) {LOGGER.error("E9OAuth2CustomZWH getUserInfo 用户校验接口自定义实现 Start");Map<String, String> reMap = new HashMap<>();TenantRpcContext.setTargetTenantKey("ts5e31tgev");TenantRpcContext.setTargetEmployeeId("1144706709679783947");LOGGER.error("添加租户ID与用户ID成功");String codeKey = prop.getCODE_KEY();String code = request.getParameter(codeKey);LOGGER.error("code ---> " + code);if (StringUtils.isBlank(code)) {return null;}String ssoAddress = prop.getSSO_ADDRESS();String clintIdKey = prop.getCLINT_ID_KEY();String clintIdValue = prop.getCLINT_ID_VALUE();String clintSecretKey = prop.getCLINT_SECRET_KEY();String clintSecretValue = prop.getCLINT_SECRET_VALUE();String accessTokenUrl = ssoAddress + "/login/oauth/access_token";String params = clintIdKey + "=" + clintIdValue + "&" +clintSecretKey + "=" + clintSecretValue + "&" +"code=" + code;String accessTokenResult = HttpsUtil.getResult(accessTokenUrl, "POST", params, null);LOGGER.error("accessTokenResult ---> " + accessTokenResult);if (StringUtils.isBlank(accessTokenResult)) {//失败降级处理return null;}JSONObject accessTokenJson = JSONObject.parseObject(accessTokenResult);if (!accessTokenJson.containsKey("access_token")) {//失败降级处理return null;}//access_token令牌String accessTokenValue = accessTokenJson.getString("access_token");LOGGER.error("getUserInfo accessTokenValue ---> " + accessTokenValue);//code授权码校验,换取access_tokenString profileUrl = ssoAddress + "/user/info?access_token=" + accessTokenValue;LOGGER.error("profileUrl ---> " + profileUrl);Map<String, String> headerMap = new HashMap<>();headerMap.put("Authorization", "Bearer " + accessTokenValue);String profileResult = HttpsUtil.getResult(profileUrl, "GET", null, headerMap);LOGGER.error("getUserInfo profileResult ---> " + profileResult);if (StringUtils.isBlank(profileResult)) {//失败降级处理return null;}JSONObject profileJson = JSONObject.parseObject(profileResult);LOGGER.error("getUserInfo profileJson ---> " + profileJson);//登录名、用户名String loginId = profileJson.getString("login");String userName = profileJson.getString("name");LOGGER.error("getUserInfo loginId ---> " + loginId + " userName ---> " + userName);// 为登录名添加前缀loginId = "atomgit-" + loginId;LOGGER.error("loginId ---> " + loginId);// 获取数据源基本信息String groupId = "993755046913105920";// 查询人员是否存在String querySQL = "SELECT employee_id FROM user_info_login_param WHERE login_value = ? AND login_type = 'loginName' AND tenant_key = 'ts5e31tgev' AND delete_type = 0";List<SqlParamEntity> sqlParams = new ArrayList<>();SqlParamEntity sqlParam1 = new SqlParamEntity();sqlParam1.setParamType(SqlParamType.STRING);sqlParam1.setValue(loginId);sqlParams.add(sqlParam1);LOGGER.error("querySQL ---> " + querySQL);List<Map<String, Object>> queryRes = dbHelper.selectBySql(groupId, querySQL, SourceType.EXTERNAL, sqlParams);String userId = "";if (queryRes != null && !queryRes.isEmpty()) {Map<String, Object> queryMap = queryRes.get(0);userId = String.valueOf(queryMap.get("employee_id"));}LOGGER.error("userId ---> " + userId);// 不存在添加if ("".equals(userId)) {syncUserInfo(userName, loginId);} else {// 判断人员是否已离职String sql2 = "SELECT username FROM employee WHERE id = ? AND tenant_key = 'ts5e31tgev' AND delete_type = 0 AND status = 'normal'";LOGGER.error("sql2 ---> " + sql2);List<SqlParamEntity> sqlParams2 = new ArrayList<>();SqlParamEntity sqlParam2 = new SqlParamEntity();sqlParam2.setParamType(SqlParamType.STRING);sqlParam2.setValue(userId);sqlParams2.add(sqlParam2);List<Map<String, Object>> queryRes2 = dbHelper.selectBySql("993670126492573696", sql2, SourceType.EXTERNAL, sqlParams2);String username = "";if (queryRes2 != null && !queryRes2.isEmpty()) {Map<String, Object> queryMap = queryRes2.get(0);username = String.valueOf(queryMap.get("username"));}LOGGER.error("username ---> " + username);// 人员已离职if(username == null || username.isEmpty()){TenantRpcContext.removeTargetTenantKey();TenantRpcContext.removeTargetEmployeeId();reMap.put("code", "10001");reMap.put("status", "400");LOGGER.error("getUserInfo 人员已离职 reMap ---> " + JSONObject.toJSONString(reMap));return reMap;}}// 认证成功reMap.put("accountType", "1"); //1:登录名 4:工号 5:电子邮箱 6:手机号码reMap.put("username", loginId);reMap.put("status", "200");LOGGER.error("getUserInfo reMap ---> " + JSONObject.toJSONString(reMap));TenantRpcContext.removeTargetTenantKey();TenantRpcContext.removeTargetEmployeeId();LOGGER.error("移出租户ID与用户ID成功");return reMap;}@SneakyThrows@Overridepublic Map<String, String> logout(HttpServletRequest request, HttpServletResponse response) {Map<String, String> reMap = new HashMap<>();String ssoAddressCode = prop.getSSO_ADDRESS_CODE();String logoutUrl = ssoAddressCode + "/logout?redirect_uri=" + URLEncoder.encode("http://xxx.com", "UTF-8");reMap.put("logoutUrl", logoutUrl);reMap.put("isLogout", "1"); //是否跳转登出URL 0:不登出 1:登出LOGGER.error("---------------logout reMap:{}", reMap);return reMap;}@Overridepublic Boolean isRedirectLogin() {return true;}
}
SecondevZwhCustomPropertiesConfigCenter 注册自定义配置文件信息
package com.weaver.custom.configcenter;
import com.weaver.framework.client.annotation.WeaverConfigCenter;@WeaverConfigCenter(sources = {@WeaverConfigCenter.ConfigProperty(dataId = "weaver-secondev-zwh.properties",group = "DEFAULT_GROUP",refresh = "true")
})
public class SecondevZwhCustomPropertiesConfigCenter {
}
OAuth2CustomProperty 读取配置文件类package com.weaver.intunifyauth.client.custom.service.impl.xxx.constant;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;@Data
@Configuration
@RefreshScope
public class OAuth2CustomProperty {/*** 统一认证参数*/@Value("${CLINT_ID_KEY}")private String CLINT_ID_KEY;@Value("${CLINT_ID_VALUE}")private String CLINT_ID_VALUE;@Value("${STATE_KEY}")private String STATE_KEY;@Value("${STATE_VALUE}")private String STATE_VALUE;@Value("${CLINT_SECRET_KEY}")private String CLINT_SECRET_KEY;@Value("${CLINT_SECRET_VALUE}")private String CLINT_SECRET_VALUE;@Value("${REDIRECT_URI_KEY}")private String REDIRECT_URI_KEY;@Value("${REDIRECT_URI_VALUE}")private String REDIRECT_URI_VALUE;@Value("${CODE_KEY}")private String CODE_KEY;@Value("${SSO_ADDRESS}")private String SSO_ADDRESS;@Value("${SSO_ADDRESS_CODE}")private String SSO_ADDRESS_CODE;/*** 人员信息同步参数*/@Value("${API_URL}")private String API_URL;@Value("${CORP_ID}")private String CORP_ID;@Value("${APP_KEY}")private String APP_KEY;@Value("${APP_SECRET}")private String APP_SECRET;@Value("${SYNC_EMPLOYEE_URL}")private String SYNC_EMPLOYEE_URL;@Value("${DEPARTMENT_CODE}")private String DEPARTMENT_CODE;
}
🔉下面是一些工具类:
- CommonUtil 同步人员信息
- DbHelper 操作数据库
- HttpsUtil 发送 Https 请求
- MyX509TrustManager 绕过证书
- SpringContextUtil 获取Bean
package com.weaver.intunifyauth.client.custom.service.impl.xxx.util;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.intunifyauth.client.custom.service.impl.xxx.constant.OAuth2CustomProperty;
import com.weaver.openapi.pojo.auth.params.AccessTokenParam;
import com.weaver.openapi.pojo.auth.params.CodeParam;
import com.weaver.openapi.pojo.auth.res.AccessToken;
import com.weaver.openapi.pojo.auth.res.Code;
import com.weaver.openapi.service.AuthService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.nio.charset.StandardCharsets;public class CommonUtil {private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class);private static final OAuth2CustomProperty prop = SpringContextUtil.getBean(OAuth2CustomProperty.class);public static String syncUserInfo(String userName, String loginid){if("".equals(loginid) || "".equals(userName)){return "";}logger.error("CommonUtil syncUserInfo 人员信息同步 Start");String corpId = prop.getCORP_ID();String apiUr = prop.getAPI_URL();String appKey = prop.getAPP_KEY();String appSecret = prop.getAPP_SECRET();String syncEmployeeUrl = prop.getSYNC_EMPLOYEE_URL();String departmentCode = prop.getDEPARTMENT_CODE();CodeParam codeParam = new CodeParam(corpId, "code", "1");Code code = AuthService.getAuthCode(codeParam, apiUr, null);logger.error("code ---> " + code.getCode());AccessTokenParam tokenParam = new AccessTokenParam(appKey,appSecret, "authorization_code", code.getCode());AccessToken token = AuthService.getAuthAccessToken(tokenParam, apiUr, null);logger.error("accessToken ---> " + token.getAccessToken());logger.error("refreshToken ---> " + token.getRefreshToken());try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpPost httpPost = new HttpPost(syncEmployeeUrl + "?access_token=" + token.getAccessToken());JSONObject params = new JSONObject();JSONArray data = new JSONArray();JSONObject user = new JSONObject();JSONObject checkParams = new JSONObject();checkParams.put("employee", "username");checkParams.put("department", "code");user.put("username", userName);user.put("account", loginid);user.put("loginid", loginid);user.put("department", departmentCode);user.put("personnel_status", "3");data.add(user);params.put("data", data);params.put("dataRule", checkParams);StringEntity entity = new StringEntity(params.toJSONString(),ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));httpPost.setEntity(entity);httpPost.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());try (CloseableHttpResponse response = httpClient.execute(httpPost)) {HttpEntity responseEntity = response.getEntity();String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);EntityUtils.consume(responseEntity);return responseBody;}} catch (Exception e) {logger.error("CommonUtil syncUserInfo 程序出错 ---> " + e.getClass().getName() + " 具体信息 ---> " + e.getMessage());e.printStackTrace();return "";}}}
package com.weaver.intunifyauth.client.custom.service.impl.xxx.util;import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.weaver.ebuilder.datasource.api.entity.ExecuteSqlEntity;
import com.weaver.ebuilder.datasource.api.entity.SqlParamEntity;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import com.weaver.workflow.common.util.DataTransUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Component
public class DbHelper {// select insert update// 固定字段 id ,delete_type ,tenant_key ,create_time ,update_time// delete ==> update eteams.employee delete_type = 0 1 逻辑删除 3 物理删除// where tenant_key ='xxxx' and delete_type = 0// insert create_time// update update_timeprivate Map<String, String> logicGroupMap = null;private Map<String, String> externalGroupMap = null;private static final Logger logger = LoggerFactory.getLogger(DbHelper.class);@Autowiredprivate DataSetService dataSetService;public boolean clearGroup() {logicGroupMap = null;externalGroupMap = null;return true;}/*** 获取外部数据源信息** @param dbName 数据库名* @return groupId*/public String getExternalGroupIdByName(String dbName) {if (externalGroupMap == null) {List<Map<String, Object>> dataGroups = dataSetService.getDataGroups(SourceType.EXTERNAL, false);externalGroupMap = new HashMap<>();for (Map<String, Object> dataGroup : dataGroups) {String name = DataTransUtil.null2String(dataGroup.get("name"));String id = DataTransUtil.null2String(dataGroup.get("id"));if (!name.isEmpty() && !id.isEmpty()) {externalGroupMap.put(name, id);}}}return DataTransUtil.null2String(externalGroupMap.get(dbName));}/*** 获取内部模块数据源信息** @param dbName 数据库名* @return groupId*/public String getLogicGroupIdByName(String dbName) {if (logicGroupMap == null) {List<Map<String, Object>> dataGroups = dataSetService.getDataGroups(SourceType.LOGIC, false);logicGroupMap = new HashMap<>();for (Map<String, Object> dataGroup : dataGroups) {String id = DataTransUtil.null2String(dataGroup.get("id"));if (!id.isEmpty()) {logicGroupMap.put(id, id);}}}return DataTransUtil.null2String(logicGroupMap.get(dbName));}/*** 执行查询sql 返回数据** @param groupId groupId* @param sql sql* @param sourceType LOGIC:内部 EXTERNAL:外部* @return 查询结果*/public List<Map<String, Object>> selectBySql(String groupId, String sql, SourceType sourceType, List<SqlParamEntity> sqlParams) {List<Map<String, Object>> mapList = Lists.newArrayList();logger.error("selectBySql 查询SQL groupId ---> " + groupId + " sql ---> " + sql + " sourceType ---> " + sourceType);ExecuteSqlEntity entity = new ExecuteSqlEntity();entity.setSourceType(sourceType);entity.setGroupId(groupId);entity.setSql(Base64.encode(sql));entity.setParams(sqlParams);Map<String, Object> external = dataSetService.executeSql(entity);logger.error("external ---> " + external);if (external.containsKey("records")) {JSONArray records = JSONArray.parseArray(JSON.toJSONString(external.get("records")));logger.error("records ---> " + records.toJSONString());for (int i = 0; i < records.size(); i++) {JSONObject jsonObject = records.getJSONObject(i);Map<String, Object> map = Maps.newHashMap();for (String s : jsonObject.getInnerMap().keySet()) {map.put(s, jsonObject.get(s));}mapList.add(map);}}logger.error("mapList ---> " + Arrays.toString(mapList.toArray()));return mapList;}/*** 执行sql 不返回数据** @param groupId groupId* @param sql sql* @param sourceType LOGIC:内部 EXTERNAL:外部* @return 执行结果*/public boolean executeSql(String groupId, String sql, SourceType sourceType) {ExecuteSqlEntity entity = new ExecuteSqlEntity();entity.setSourceType(sourceType);entity.setGroupId(groupId);entity.setSql(Base64.encode(sql));Map<String, Object> external = dataSetService.executeSql(entity);return true;}
}
package com.weaver.intunifyauth.client.custom.service.impl.xxx.util;import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;public class HttpsUtil {private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);public static String httpRequest(String requestUrl, String requestMethod, String outputStr, Map<String, String> headerMap) throws Exception {String response = "";InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;InputStream inputStream = null;HttpURLConnection httpUrlConn = null;try {StringBuffer buffer = new StringBuffer();URL url = new URL(requestUrl);httpUrlConn = (HttpURLConnection) url.openConnection();httpUrlConn.setConnectTimeout(60000);httpUrlConn.setReadTimeout(60000);httpUrlConn.setDoOutput(true);httpUrlConn.setDoInput(true);httpUrlConn.setUseCaches(false);httpUrlConn.setRequestMethod(requestMethod);if (headerMap != null && headerMap.size() > 0) {for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpUrlConn.setRequestProperty(entry.getKey(), entry.getValue());}}if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();if (outputStr != null) {OutputStream outputStream = httpUrlConn.getOutputStream();outputStream.write(outputStr.getBytes("UTF-8"));outputStream.close();}int responseCode = httpUrlConn.getResponseCode();logger.error("-----------responseCode:{}", responseCode);// 将返回的输入流转换成字符串if (responseCode >= 400) {inputStream = httpUrlConn.getErrorStream();} else {inputStream = httpUrlConn.getInputStream();}inputStreamReader = new InputStreamReader(inputStream, "utf-8");bufferedReader = new BufferedReader(inputStreamReader);String str = null;while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}response = buffer.toString();logger.error("-----------response:{}", response);} catch (Exception e) {logger.error("-----------httpRequest Exception:{}", e.getMessage(), e);} finally {bufferedReader.close();inputStreamReader.close();// 释放资源inputStream.close();inputStream = null;httpUrlConn.disconnect();}return response;}public static String httpsRequest(String requestUrl, String requestMethod, String outputStr, Map<String, String> headerMap) throws Exception {String response = "";InputStreamReader inputStreamReader = null;BufferedReader bufferedReader = null;InputStream inputStream = null;HttpsURLConnection httpUrlConn = null;try {HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {public boolean verify(String hostname,SSLSession sslsession) {return true;}});StringBuffer buffer = new StringBuffer();TrustManager[] tm = {new MyX509TrustManager()};SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");sslContext.init(null, tm, new java.security.SecureRandom());SSLSocketFactory ssf = sslContext.getSocketFactory();URL url = new URL(requestUrl);httpUrlConn = (HttpsURLConnection) url.openConnection();httpUrlConn.setSSLSocketFactory(ssf);httpUrlConn.setConnectTimeout(60000);httpUrlConn.setReadTimeout(60000);httpUrlConn.setDoOutput(true);httpUrlConn.setDoInput(true);httpUrlConn.setUseCaches(false);httpUrlConn.setRequestMethod(requestMethod);if (headerMap != null && headerMap.size() > 0) {for (Map.Entry<String, String> entry : headerMap.entrySet()) {httpUrlConn.setRequestProperty(entry.getKey(), entry.getValue());}}if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect();if (outputStr != null) {OutputStream outputStream = httpUrlConn.getOutputStream();outputStream.write(outputStr.getBytes("UTF-8"));outputStream.close();}int responseCode = httpUrlConn.getResponseCode();logger.error("-----------responseCode:{}", responseCode);// 将返回的输入流转换成字符串if (responseCode >= 400) {inputStream = httpUrlConn.getErrorStream();} else {inputStream = httpUrlConn.getInputStream();}inputStreamReader = new InputStreamReader(inputStream, "utf-8");bufferedReader = new BufferedReader(inputStreamReader);String str = null;while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}response = buffer.toString();logger.error("-----------response:{}", response);} catch (Exception e) {logger.error("-----------httpsRequest Exception:{}", e.getMessage(), e);} finally {bufferedReader.close();inputStreamReader.close();// 释放资源inputStream.close();inputStream = null;httpUrlConn.disconnect();}return response;}/*** 获取接口请求结果* @param requestUrl 请求地址* @param requestMethod 请求方法* @param paramsStr 请求参数* @param headerMap 请求头* @return*/public static String getResult(String requestUrl, String requestMethod, String paramsStr, Map<String, String> headerMap) {logger.error("-----------requestUrl:{}", requestUrl);logger.error("-----------requestMethod:{}", requestMethod);logger.error("-----------requestParams:{}", paramsStr);if ("GET".equalsIgnoreCase(requestMethod) && StringUtils.isNotEmpty(paramsStr)) {requestUrl += (requestUrl.indexOf("?") > 0 ? "&" : "?") + paramsStr;paramsStr = null;}String result = "";if (requestUrl.startsWith("https")) {try {result = httpsRequest(requestUrl, requestMethod, paramsStr, headerMap);} catch (Exception e) {logger.error("-----------HttpsUtil Exception:{}", e.getMessage(), e);}} else {try {result = httpRequest(requestUrl, requestMethod, paramsStr, headerMap);} catch (Exception e) {logger.error("-----------HttpsUtil Exception:{}", e.getMessage(), e);}}return result;}}
package com.weaver.intunifyauth.client.custom.service.impl.xxx.util;import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;public class MyX509TrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return null;}
} package com.weaver.intunifyauth.client.custom.service.impl.xxx.util;import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;@Component
public class SpringContextUtil implements ApplicationContextAware {private static ApplicationContext context;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {context = applicationContext;}public static <T> T getBean(Class<T> beanClass) {return context.getBean(beanClass);}
}