KJB 필터 및 Util 정리
This commit is contained in:
+1
-1
Submodule elink-online-common updated: 037fcd6302...bf03a97fa3
-867
@@ -1,867 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.client.impl;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.StringReader;
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
import java.net.ConnectException;
|
|
||||||
import java.net.SocketTimeoutException;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
|
||||||
import org.apache.commons.lang3.ArrayUtils;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.apache.commons.lang3.time.StopWatch;
|
|
||||||
import org.apache.hc.client5.http.classic.HttpClient;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPost;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpPut;
|
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
|
||||||
import org.apache.hc.client5.http.config.RequestConfig;
|
|
||||||
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
|
|
||||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
|
|
||||||
import org.apache.hc.core5.http.ContentType;
|
|
||||||
import org.apache.hc.core5.http.Header;
|
|
||||||
import org.apache.hc.core5.http.HttpHost;
|
|
||||||
import org.apache.hc.core5.http.NameValuePair;
|
|
||||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
|
||||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
|
||||||
import org.apache.hc.core5.http.message.BasicNameValuePair;
|
|
||||||
import org.apache.hc.core5.http.protocol.BasicHttpContext;
|
|
||||||
import org.apache.hc.core5.http.protocol.HttpContext;
|
|
||||||
import org.apache.hc.core5.net.URIBuilder;
|
|
||||||
import org.dom4j.Document;
|
|
||||||
import org.dom4j.Element;
|
|
||||||
import org.dom4j.io.SAXReader;
|
|
||||||
import org.json.simple.JSONArray;
|
|
||||||
import org.json.simple.JSONObject;
|
|
||||||
import org.json.simple.JSONValue;
|
|
||||||
import org.springframework.web.util.UriComponents;
|
|
||||||
import org.springframework.web.util.UriComponentsBuilder;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterGroupVO;
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.HttpMemoryLogger;
|
|
||||||
import com.eactive.eai.adapter.http.HttpMethodType;
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClient5AdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.client.HttpClientAdapterVO;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.authserver.vo.ClientVO;
|
|
||||||
import com.eactive.eai.common.TransactionContextKeys;
|
|
||||||
import com.eactive.eai.common.authoutbound.AccessTokenManagerByDB;
|
|
||||||
import com.eactive.eai.common.dao.DAOException;
|
|
||||||
import com.eactive.eai.common.exception.ExceptionUtil;
|
|
||||||
import com.eactive.eai.common.message.MessageType;
|
|
||||||
import com.eactive.eai.common.util.CommonLib;
|
|
||||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountTransform;
|
|
||||||
import com.jayway.jsonpath.DocumentContext;
|
|
||||||
import com.jayway.jsonpath.JsonPath;
|
|
||||||
import com.openbanking.eai.common.token.AccessTokenManager;
|
|
||||||
import com.openbanking.eai.common.token.AccessTokenVO;
|
|
||||||
import com.openbanking.eai.common.token.OAuth2AccessTokenVO;
|
|
||||||
|
|
||||||
// Kbank 가상계좌 OUTBOUND
|
|
||||||
public class HttpClient5AdapterServiceVirtualAccount extends HttpClient5AdapterServiceSupport
|
|
||||||
implements HttpClientAdapterServiceKey {
|
|
||||||
public static final String TYPE_VARIABLE_URL_REQUEST = "variableUrlRequest";
|
|
||||||
public static final String TYPE_SIMPLE_REQUEST = "simpleRequest";
|
|
||||||
|
|
||||||
public static final String REST_OPTION = "REST_OPTION";
|
|
||||||
|
|
||||||
////public static final String HEADER_CONTENT_TYPE = "Content-Type";
|
|
||||||
public static final String HEADER_GROUP = "HEADER_GROUP";
|
|
||||||
public static final String HTTP_STATUS = "HTTP_STATUS";
|
|
||||||
public static final String HEADER_KEYS = "HEADER_KEYS";
|
|
||||||
|
|
||||||
private String getSecurityKey(String adapterGroupName) throws DAOException {
|
|
||||||
String clientId = null;
|
|
||||||
String aesKey = null;
|
|
||||||
AdapterGroupVO adapterGroup = null;;
|
|
||||||
adapterGroup = AdapterManager.getInstance().getAdapterGroup(adapterGroupName);
|
|
||||||
|
|
||||||
clientId = adapterGroup.getClientId();
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
try {
|
|
||||||
ClientVO client = manager.getClientInfo(clientId);
|
|
||||||
aesKey = client.getSecurityKey();
|
|
||||||
return aesKey;
|
|
||||||
} catch (DAOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
|
|
||||||
HttpClientAdapterVO vo = super.setting(prop, tempProp);
|
|
||||||
|
|
||||||
String headerGroupName = prop.getProperty(HEADER_GROUP);
|
|
||||||
String relayResponseHeaderKeys = prop.getProperty(HEADER_KEYS, "");
|
|
||||||
boolean useAdapterToken = StringUtils.equalsIgnoreCase(prop.getProperty("ADAPTER_TOKEN_USE_YN", "N"), "Y");
|
|
||||||
|
|
||||||
boolean useForwardProxy = StringUtils.equalsIgnoreCase(prop.getProperty("FORWARD_PROXY_USE_YN", "N"), "Y");
|
|
||||||
String forwardProxyUrl = prop.getProperty("FORWARD_PROXY_URL");
|
|
||||||
|
|
||||||
// ex) $.dataHeader.GW_RSLT_CD
|
|
||||||
String tokenErrorCodeKey = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_KEY");
|
|
||||||
String tokenErrorCodeValues = prop.getProperty("ADAPTER_TOKEN_ERROR_CODE_VALUES");
|
|
||||||
String tokenErrorHttpStatusCode = prop.getProperty("ADAPTER_TOKEN_ERROR_HTTP_STATUS_CODE"); // 200 or 400번대
|
|
||||||
|
|
||||||
// 레이아웃 메시지 타입 REST URL 추출 시 활용. Default JSON
|
|
||||||
String messageType = prop.getProperty("MESSAGE_TYPE", MessageType.JSON);
|
|
||||||
String inboundMethod = tempProp.getProperty(HttpAdapterServiceKey.INBOUND_METHOD, "POST");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @formatter:off
|
|
||||||
* TSEAIHE02.RESTOPTION 정보 => JSON 형태로 구성
|
|
||||||
* - type : simpleRequest, variableUrlRequest
|
|
||||||
* - extraPath : 어댑터 프로퍼티 URL에 추가될 HTTP REST URL
|
|
||||||
* - method : get, delete, post, put
|
|
||||||
* - contentType: application/json(default), application/x-www-form-urlencoded
|
|
||||||
* - adapterTokenUseYn: Y, N(default)
|
|
||||||
* ex)
|
|
||||||
* {"type":"simpleRequest","extraPath":"v2.0/accout/balance","method":"post"}
|
|
||||||
* @formatter:on
|
|
||||||
*/
|
|
||||||
|
|
||||||
String restOptionData = tempProp.getProperty(REST_OPTION);
|
|
||||||
|
|
||||||
JSONObject restOptionObject = parseJson(restOptionData);
|
|
||||||
if (restOptionObject == null) {
|
|
||||||
throw new Exception("OptionData parsing result is NULL");
|
|
||||||
}
|
|
||||||
|
|
||||||
String rmethod = (String) restOptionObject.getOrDefault("method", inboundMethod);
|
|
||||||
String contentType = (String) restOptionObject.getOrDefault("contentType", "application/json");
|
|
||||||
String adapterTokenUseYn = (String) restOptionObject.get("adapterTokenUseYn");
|
|
||||||
if (StringUtils.isNotBlank(adapterTokenUseYn)) { // interface 에 설정된게 우선한다.
|
|
||||||
useAdapterToken = StringUtils.equalsIgnoreCase(adapterTokenUseYn, "Y");
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpClient mclient = this.client;
|
|
||||||
String sendData = "";
|
|
||||||
if (data instanceof String) {
|
|
||||||
sendData = (String) data;
|
|
||||||
} else if (data instanceof byte[]) {
|
|
||||||
sendData = new String((byte[]) data, vo.getEncode());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 필드암복호화 처리 (dec CubeOne -> enc AES)
|
|
||||||
String encPaths = prop.getProperty("ENC_PATHS");
|
|
||||||
List<String> encFieldList = null;
|
|
||||||
String aesKey = getSecurityKey(vo.getAdapterGroupName());
|
|
||||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] ENC AdapterGroupName[" + vo.getAdapterGroupName()+ "], aesKey["+aesKey+"]");
|
|
||||||
if(StringUtils.isNotBlank(aesKey) && StringUtils.isNotBlank(encPaths)) {
|
|
||||||
String[] items = encPaths.split(",");
|
|
||||||
encFieldList = Arrays.asList(items);
|
|
||||||
sendData = VirtualAccountTransform.toAES(aesKey, encFieldList, sendData);
|
|
||||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] after toAES = [" + sendData + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
////mclient.getParams().setContentCharset(vo.getEncode());
|
|
||||||
|
|
||||||
JSONObject dataObject = null;
|
|
||||||
Object httpHeader = null;
|
|
||||||
if (MessageType.JSON.equals(messageType)) {
|
|
||||||
dataObject = parseJson(sendData);
|
|
||||||
if (dataObject != null && StringUtils.isNotBlank(headerGroupName)) {
|
|
||||||
httpHeader = dataObject.get(headerGroupName);
|
|
||||||
dataObject.remove(headerGroupName);
|
|
||||||
}
|
|
||||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] dataObject1 = [" + dataObject + "]");
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] sendData = [" + sendData + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// interface 에 설정된게 우선한다.
|
|
||||||
String uri = null;
|
|
||||||
if (dataObject == null) {
|
|
||||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, sendData);
|
|
||||||
} else {
|
|
||||||
uri = changeUrl(messageType, vo.getUrl(), restOptionData, dataObject);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (logger.isDebug()) logger.debug("HttpClientAdapterServiceRest] dataObject2 = [" + dataObject + "]");
|
|
||||||
|
|
||||||
//////if (vo.getConnectionTimeout() != 0) {
|
|
||||||
// mclient.getHttpConnectionManager().getParams().setConnectionTimeout(vo.getConnectionTimeout());
|
|
||||||
//}
|
|
||||||
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug(
|
|
||||||
"HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL=[" + vo.getUrl() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") PARAMETER_NAME=["
|
|
||||||
+ vo.getParameterName() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") ENCODE=["
|
|
||||||
+ vo.getEncode() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") RESPONSE_TYPE=["
|
|
||||||
+ vo.getResponseType() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") URL_ENCODE_YN=["
|
|
||||||
+ vo.getUrlEncodeYn() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") CONNECTION_TIMEOUT=["
|
|
||||||
+ vo.getConnectionTimeout() + "] ");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") REST_OPTION=["
|
|
||||||
+ restOptionData + "] ");
|
|
||||||
}
|
|
||||||
|
|
||||||
HttpUriRequestBase method = null;
|
|
||||||
|
|
||||||
// 메소드 타입에 따라 HttpRequestBase 인스턴스 생성
|
|
||||||
switch (HttpMethodType.getValue(rmethod)) {
|
|
||||||
case GET:
|
|
||||||
method = new HttpGet(uri);
|
|
||||||
break;
|
|
||||||
case DELETE:
|
|
||||||
method = new HttpDelete(uri);
|
|
||||||
break;
|
|
||||||
case POST:
|
|
||||||
method = new HttpPost(uri);
|
|
||||||
break;
|
|
||||||
case PUT:
|
|
||||||
method = new HttpPut(uri);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
method = new HttpGet(uri);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
|
|
||||||
|
|
||||||
if (useForwardProxy) {
|
|
||||||
java.net.URL url = new java.net.URL(forwardProxyUrl);
|
|
||||||
|
|
||||||
// 프로토콜, 호스트, 포트 추출
|
|
||||||
String protocol = url.getProtocol();
|
|
||||||
String host = url.getHost();
|
|
||||||
int port = url.getPort();
|
|
||||||
HttpHost proxy = new HttpHost(protocol, host, port);
|
|
||||||
requestConfigBuilder.setProxy(proxy);
|
|
||||||
}
|
|
||||||
|
|
||||||
configureHttpClient(requestConfigBuilder, vo, method);
|
|
||||||
|
|
||||||
switch (HttpMethodType.getValue(rmethod)) {
|
|
||||||
case GET:
|
|
||||||
case DELETE:
|
|
||||||
HashMap<String, String> h = getParameters(dataObject);
|
|
||||||
URIBuilder uriBuilder = new URIBuilder(uri);
|
|
||||||
for (Map.Entry<String, String> entry : h.entrySet()) {
|
|
||||||
uriBuilder.addParameter(entry.getKey(), entry.getValue());
|
|
||||||
}
|
|
||||||
URI fullUri = uriBuilder.build();
|
|
||||||
if (method instanceof HttpGet) {
|
|
||||||
((HttpGet) method).setUri(fullUri);
|
|
||||||
} else if (method instanceof HttpDelete) {
|
|
||||||
((HttpDelete) method).setUri(fullUri);
|
|
||||||
}
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] (get Method) QueryString = [" + fullUri.getQuery() + "]");
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case PUT:
|
|
||||||
case POST:
|
|
||||||
assignPostBody(dataObject, contentType, vo.getEncode(), method);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") method.getParams()=["
|
|
||||||
+ method.getEntity() + "] ");
|
|
||||||
}
|
|
||||||
|
|
||||||
OAuth2AccessTokenVO accessToken = null;
|
|
||||||
if (useAdapterToken) {
|
|
||||||
AccessTokenManagerByDB tokenManager = AccessTokenManagerByDB.getInstance();
|
|
||||||
accessToken = (OAuth2AccessTokenVO) tokenManager.getAccessTokenVO(vo.getAdapterGroupName());
|
|
||||||
|
|
||||||
// 토큰이 없거나 만료 됐으면 재발급
|
|
||||||
if (accessToken == null || accessToken.isExpired()) {
|
|
||||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
|
||||||
accessToken = (OAuth2AccessTokenVO) tokenManager.retryAccessTokenVO(vo.getAdapterGroupName(), prop,
|
|
||||||
oldToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") TOKEN = ["
|
|
||||||
+ accessToken + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
setAuthHeaders(method, accessToken);
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
|
||||||
+ ") RequestHeader [Authorization=" + method.getHeader("Authorization") + "]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 전달 header 셋팅
|
|
||||||
// Adapter 레벨 header 보다 data로 넘어온 httpHeader를 우선 적용(header명이 같다면 덮어씀)
|
|
||||||
assignRequestHeaders(method, httpHeader);
|
|
||||||
|
|
||||||
int status = -1;
|
|
||||||
|
|
||||||
try {
|
|
||||||
byte[] responseMessage = null;
|
|
||||||
Header[] responseHeaders;
|
|
||||||
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
if (dataObject != null) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = ["
|
|
||||||
+ dataObject.toJSONString() + "]");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
|
||||||
+ CommonLib.getDumpMessage(dataObject.toJSONString()));
|
|
||||||
} else {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = [" + sendData
|
|
||||||
+ "]");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName() + ") = "
|
|
||||||
+ CommonLib.getDumpMessage(sendData));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
StopWatch stopWatch = new StopWatch();
|
|
||||||
stopWatch.start();
|
|
||||||
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
|
||||||
"SEND [" + sendData + "]" + CommonLib.getDumpMessage(sendData));
|
|
||||||
}
|
|
||||||
|
|
||||||
String uuid = tempProp.getProperty(TransactionContextKeys.TRANSACTION_UUID);
|
|
||||||
HttpContext context = new BasicHttpContext();
|
|
||||||
context.setAttribute(TransactionContextKeys.TRANSACTION_UUID, uuid);
|
|
||||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_GROUP_NAME, vo.getAdapterGroupName());
|
|
||||||
context.setAttribute(HttpClientAdapterServiceKey.ADAPTER_NAME, vo.getAdapterName());
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("[method getName]" + method.getMethod());
|
|
||||||
logger.debug("[method getEntity]" + method.getEntity());
|
|
||||||
logger.debug("[method getRequestHeaders]" + method.getHeaders().toString());
|
|
||||||
logger.debug("[method getURI]" + method.getPath());
|
|
||||||
}
|
|
||||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method, context)) {
|
|
||||||
status = response.getCode();
|
|
||||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
|
||||||
responseHeaders = response.getHeaders();
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("[received status]" + status);
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = ["
|
|
||||||
+ responseMessage + "]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (ConnectException e) {
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
|
||||||
}
|
|
||||||
throw new Exception("excuteMethod java.net.ConnectException = " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
stopWatch.stop();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @formatter:off
|
|
||||||
* OAuth 토큰 응답 체크(Adapter properties로 설정)
|
|
||||||
* 응답코드에 따라 유효한 토큰 확인(토큰 재발급 여부 확인)
|
|
||||||
* API 서비스 마다 정책이 다름(보통 400대에서 체크하나 200에서도 체크할 수 있음)
|
|
||||||
*
|
|
||||||
* TOKEN_ERROR_CODE_KEY: 응답 json error code key
|
|
||||||
* __ex) $.dataHeader.resultCode
|
|
||||||
* TOKEN_ERROR_CODE_VALUES: 토큰 재발급이 필요한 응답 error codes(ex: O0001,O0002,O0003)
|
|
||||||
* TOKEN_ERROR_HTTP_STATUS_CODE: 보통 400대에서 체크하나 API 제공자에 따라 200에서도 체클할수 있음
|
|
||||||
* ex) TOKEN_ERROR_HTTP_STATUS_CODE = 200
|
|
||||||
* @formatter:on
|
|
||||||
*/
|
|
||||||
boolean needReissue = false;
|
|
||||||
|
|
||||||
Properties responseHeaderProp = assignRelayDataToInbound(tempProp, responseHeaders);
|
|
||||||
String responseString = new String(responseMessage, vo.getEncode());
|
|
||||||
|
|
||||||
Map<String, Object> map = new HashMap<String, Object>();
|
|
||||||
tempProp.put(HttpAdapterServiceKey.OUTBOUND_PROPERTY_MAP, map);
|
|
||||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_HEADERS, responseHeaderProp);
|
|
||||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_MESSAGE, responseString);
|
|
||||||
map.put(HttpAdapterServiceKey.OUTBOUND_RESPONSE_STATUS, status);
|
|
||||||
|
|
||||||
if (status == 200) {
|
|
||||||
if (useAdapterToken && StringUtils.equals(tokenErrorHttpStatusCode, "200")) {
|
|
||||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
|
||||||
vo.getEncode());
|
|
||||||
}
|
|
||||||
} else if (status == 302) {
|
|
||||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
|
||||||
relayResponseHeaderKeys += ",Location";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String errMsg = String.format(
|
|
||||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
|
||||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseString);
|
|
||||||
// logger.error(errMsg);
|
|
||||||
|
|
||||||
if (status >= 400 && status < 500) {
|
|
||||||
if (useAdapterToken) {
|
|
||||||
needReissue = checkTokenRetry(responseMessage, tokenErrorCodeKey, tokenErrorCodeValues,
|
|
||||||
vo.getEncode());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!needReissue) {
|
|
||||||
throw new Exception(errMsg);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
|
|
||||||
throw new Exception(errMsg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----------------------------------------------------------
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] responseType =" + vo.getResponseType());
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RECV " + vo.getEncode() + "(" + vo.getAdapterGroupName()
|
|
||||||
+ ") = [" + new String(responseMessage, vo.getEncode()) + "]");
|
|
||||||
// logger.debug("HttpClientAdapterServiceRest] RECV MS949 (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "MS949") + "]");
|
|
||||||
// logger.debug("HttpClientAdapterServiceRest] RECV euc-kr (" + vo.getAdapterGroupName() + ") = [" + new String(responseMessage, "euc-kr") + "]");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = "
|
|
||||||
+ CommonLib.getDumpMessage(responseMessage));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (useAdapterToken) {
|
|
||||||
if (responseMessage == null) {
|
|
||||||
throw new Exception("responseMessage is NULL, HttpStatus=" + status);
|
|
||||||
}
|
|
||||||
|
|
||||||
// OAuth 토큰 재요청 코드 확인
|
|
||||||
if (needReissue) {
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] retry access token response code = ["
|
|
||||||
+ vo.getResponseType() + "] message = [" + new String(responseMessage, vo.getEncode())
|
|
||||||
+ "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 토큰 재발급
|
|
||||||
AccessTokenManager tokenManager = AccessTokenManager.getInstance();
|
|
||||||
String oldToken = accessToken == null ? null : accessToken.getAccessToken();
|
|
||||||
OAuth2AccessTokenVO newaccessToken = (OAuth2AccessTokenVO) tokenManager
|
|
||||||
.retryAccessTokenVO(vo.getAdapterGroupName(), prop, oldToken);
|
|
||||||
method.setHeader("Authorization", newaccessToken.getAuthorization());
|
|
||||||
|
|
||||||
setAuthHeaders(method, newaccessToken);
|
|
||||||
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] SEND (" + vo.getAdapterGroupName()
|
|
||||||
+ ") RETRY TOKEN = [" + newaccessToken + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
try (CloseableHttpResponse response = (CloseableHttpResponse) mclient.execute(method)) {
|
|
||||||
status = response.getCode();
|
|
||||||
responseMessage = EntityUtils.toByteArray(response.getEntity());
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug("[received status]" + status);
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RECV (" + vo.getAdapterGroupName() + ") = ["
|
|
||||||
+ new String(responseMessage, vo.getEncode()) + "]");
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new Exception("retry excuteMethod Exceptioin = " + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (status == 302) {
|
|
||||||
if (!StringUtils.contains(relayResponseHeaderKeys, "Location")) {
|
|
||||||
relayResponseHeaderKeys += ",Location";
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String errMsg = String.format(
|
|
||||||
"http receive status fail value=%d adapterName=%s.%s uri=%s method=%s response Data=%s",
|
|
||||||
status, vo.getAdapterGroupName(), vo.getAdapterName(), uri, rmethod, responseMessage);
|
|
||||||
throw new Exception(errMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----------------------------------------------------------
|
|
||||||
if (logger.isDebug() && "N".equals(vo.getTestCallYn())) {
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RETRY responseType =" + vo.getResponseType());
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV " + vo.getEncode() + "("
|
|
||||||
+ vo.getAdapterGroupName() + ") = [" + new String(responseMessage, vo.getEncode())
|
|
||||||
+ "]");
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] RETRY RECV (" + vo.getAdapterGroupName() + ") = "
|
|
||||||
+ CommonLib.getDumpMessage(responseMessage));
|
|
||||||
}
|
|
||||||
// ----------------------------------------------------------
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
|
||||||
"RECV [" + new String(responseMessage, vo.getEncode()) + "]"
|
|
||||||
+ CommonLib.getDumpMessage(responseMessage));
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO : toCubeOne
|
|
||||||
if(StringUtils.isNotBlank(aesKey) && encFieldList != null) {
|
|
||||||
responseMessage = VirtualAccountTransform.toCubeOne(aesKey, encFieldList, responseMessage);
|
|
||||||
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.txlog(vo.getAdapterGroupName() + vo.getAdapterName(),
|
|
||||||
"RECV ENC[" + new String(responseMessage, vo.getEncode()) + "]"
|
|
||||||
+ CommonLib.getDumpMessage(responseMessage));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return assignResponseHeaders(method, responseMessage, headerGroupName, vo.getEncode(), messageType,
|
|
||||||
relayResponseHeaderKeys, status, responseHeaderProp);
|
|
||||||
} catch (SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
|
||||||
"HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
|
||||||
+ ste.toString(),
|
|
||||||
ste);
|
|
||||||
}
|
|
||||||
logger.error("HttpClientAdapterServiceRest] SocketTimeoutException (" + vo.getAdapterGroupName() + ") : "
|
|
||||||
+ ste.toString(), ste);
|
|
||||||
throw ste;
|
|
||||||
} catch (ConnectException ce) {
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(),
|
|
||||||
"HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
|
||||||
+ ce.toString(),
|
|
||||||
ce);
|
|
||||||
}
|
|
||||||
logger.error("HttpClientAdapterServiceRest] Connection Exception (" + vo.getAdapterGroupName() + ") : "
|
|
||||||
+ ce.toString(), ce);
|
|
||||||
throw ce;
|
|
||||||
} catch (Exception e) {
|
|
||||||
if (vo.getTraceLevel() >= 3) {
|
|
||||||
HttpMemoryLogger.error(vo.getAdapterGroupName() + vo.getAdapterName(), e.toString(), e);
|
|
||||||
}
|
|
||||||
logger.error("HttpClientAdapterServiceRest] Exception (" + vo.getAdapterGroupName() + ") : " + e.toString(),
|
|
||||||
e);
|
|
||||||
throw e;
|
|
||||||
} finally {
|
|
||||||
if (status != HttpStatus.SC_OK) {
|
|
||||||
String[] msgArgs = new String[1];
|
|
||||||
msgArgs[0] = String.valueOf(status);
|
|
||||||
String resMsg = ExceptionUtil.make("RDCEAIAHA013", msgArgs);
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug(resMsg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private Properties assignRelayDataToInbound(Properties prop, Header[] responseHeaders) {
|
|
||||||
Properties headerProp = new Properties();
|
|
||||||
if (responseHeaders == null || responseHeaders.length == 0) {
|
|
||||||
return headerProp;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (Header header : responseHeaders) {
|
|
||||||
headerProp.put(header.getName(), header.getValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
return headerProp;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 현재 1단계 레이아웃에만 적용되도록 구현됨.
|
|
||||||
*
|
|
||||||
* @param method
|
|
||||||
* @param responseMessage
|
|
||||||
* @param headerGroupName
|
|
||||||
* @param encode
|
|
||||||
* @param messageType
|
|
||||||
* @param relayHeaderKeys
|
|
||||||
* @return
|
|
||||||
* @throws Exception
|
|
||||||
*/
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
private String assignResponseHeaders(HttpUriRequestBase method, byte[] responseMessage, String headerGroupName,
|
|
||||||
String encode, String messageType, String relayHeaderKeys, int status, Properties responseHeaderProp)
|
|
||||||
throws Exception {
|
|
||||||
if (!MessageType.JSON.equals(messageType) || StringUtils.isBlank(headerGroupName)
|
|
||||||
|| StringUtils.isBlank(relayHeaderKeys)) {
|
|
||||||
return new String(responseMessage, encode);
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] relayKeyArr = org.springframework.util.StringUtils.tokenizeToStringArray(relayHeaderKeys, ",");
|
|
||||||
JSONObject headerJson = new JSONObject();
|
|
||||||
for (String key : relayKeyArr) {
|
|
||||||
String value = responseHeaderProp.getProperty(key);
|
|
||||||
if (StringUtils.isNotBlank(value)) {
|
|
||||||
headerJson.put(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
headerJson.put(HTTP_STATUS, String.valueOf(status));
|
|
||||||
|
|
||||||
if (headerJson.size() <= 0) {
|
|
||||||
return new String(responseMessage, encode);
|
|
||||||
}
|
|
||||||
|
|
||||||
JSONObject message = null;
|
|
||||||
if (responseMessage == null || responseMessage.length == 0) {
|
|
||||||
message = new JSONObject();
|
|
||||||
} else {
|
|
||||||
message = parseJson(new String(responseMessage, encode));
|
|
||||||
if (message == null) {
|
|
||||||
message = new JSONObject();
|
|
||||||
message.put("Malformed_Response_Message", new String(responseMessage, encode));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(headerGroupName) && message != null)
|
|
||||||
message.put(headerGroupName, headerJson);
|
|
||||||
return message.toJSONString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setAuthHeaders(HttpUriRequestBase method, OAuth2AccessTokenVO accessToken) throws Exception {
|
|
||||||
method.setHeader("Authorization",
|
|
||||||
String.format("%s %s", AccessTokenVO.BEARER_TYPE, accessToken.getAccessToken()));
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean checkTokenRetry(byte[] responseMessage, String tokenErrorCodeKey, String tokenErrorCodeValues,
|
|
||||||
String encode) {
|
|
||||||
if (responseMessage == null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isBlank(tokenErrorCodeKey)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isBlank(tokenErrorCodeValues)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
DocumentContext jsonContext = JsonPath.parse(new String(responseMessage, encode));
|
|
||||||
String responseCode = jsonContext.read(tokenErrorCodeKey);
|
|
||||||
if (StringUtils.isBlank(responseCode)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] arr = org.springframework.util.StringUtils.tokenizeToStringArray(tokenErrorCodeValues, ",");
|
|
||||||
return ArrayUtils.contains(arr, responseCode);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("HttpClientAdapterServiceRest] checkTokenRetry error=" + e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader) {
|
|
||||||
if (httpHeader == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (httpHeader instanceof JSONObject) {
|
|
||||||
JSONObject jsonObject = (JSONObject) httpHeader;
|
|
||||||
for (Object key : jsonObject.keySet()) {
|
|
||||||
Object obj = jsonObject.get(key);
|
|
||||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
method.setHeader((String) key, (String) obj);
|
|
||||||
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("Request Header :" + (String) key + "=[" + (String) obj + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
private void assignPostBody(Object eaiBody, String contentType, String charset, HttpUriRequestBase method) {
|
|
||||||
if (eaiBody == null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.contains(contentType, "application/x-www-form-urlencoded")) {
|
|
||||||
if (eaiBody instanceof JSONObject) {
|
|
||||||
List<NameValuePair> params = new ArrayList<>();
|
|
||||||
JSONObject jsonObject = (JSONObject) eaiBody;
|
|
||||||
for (Object key : jsonObject.keySet()) {
|
|
||||||
params.add(new BasicNameValuePair((String) key, (String) jsonObject.get(key)));
|
|
||||||
}
|
|
||||||
|
|
||||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
|
|
||||||
method.setEntity(entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
ContentType contentTypeObj = ContentType.create(contentType, charset);
|
|
||||||
|
|
||||||
// 요청 본문을 StringEntity 객체로 생성
|
|
||||||
StringEntity entity = new StringEntity(eaiBody.toString(), contentTypeObj);
|
|
||||||
|
|
||||||
// 요청에 본문 추가
|
|
||||||
method.setEntity(entity);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private HashMap<String, String> getParameters(Object message) throws Exception {
|
|
||||||
|
|
||||||
HashMap<String, String> result = new HashMap<String, String>();
|
|
||||||
|
|
||||||
if (message != null) {
|
|
||||||
if (message instanceof JSONObject) {
|
|
||||||
JSONObject jsonObject = (JSONObject) message;
|
|
||||||
for (Object key : jsonObject.keySet()) {
|
|
||||||
Object obj = jsonObject.get(key);
|
|
||||||
if ((obj instanceof JSONObject) || (obj instanceof JSONArray)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
result.put((String) key, getStringValue(obj));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
String[] messages = ((String) message).split("&");
|
|
||||||
String[] data = null;
|
|
||||||
|
|
||||||
for (int i = 0; i < messages.length; i++) {
|
|
||||||
data = messages[i].split("=", 2);
|
|
||||||
if (data.length == 2) {
|
|
||||||
result.put(data[0], data[1]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getStringValue(Object obj) {
|
|
||||||
if (obj == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (obj instanceof String) {
|
|
||||||
return (String) obj;
|
|
||||||
} else if (obj instanceof Long) {
|
|
||||||
return Long.toString((Long) obj);
|
|
||||||
} else if (obj instanceof BigDecimal) {
|
|
||||||
return ((BigDecimal) obj).toPlainString();
|
|
||||||
} else {
|
|
||||||
return (String) obj;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
private JSONObject parseJson(String message) throws Exception {
|
|
||||||
if (message == null) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (JSONObject) JSONValue.parse(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Document convertXmlDocument(String message) throws Exception {
|
|
||||||
SAXReader builder = new SAXReader();
|
|
||||||
Document document = builder.read(new StringReader(message));
|
|
||||||
return document;
|
|
||||||
}
|
|
||||||
|
|
||||||
@SuppressWarnings("deprecation")
|
|
||||||
private String changeUrl(String messageType, String url, String restOption, Object sendData) {
|
|
||||||
if ((MessageType.JSON.equals(messageType) || MessageType.XML.equals(messageType))) {
|
|
||||||
try {
|
|
||||||
if (StringUtils.isBlank(restOption)) {
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
List<String> urlVariableList = new ArrayList<String>();
|
|
||||||
JSONObject restOptionObject = parseJson(restOption);
|
|
||||||
|
|
||||||
if (restOptionObject == null)
|
|
||||||
throw new Exception("restOption is NULL");
|
|
||||||
|
|
||||||
String type = (String) restOptionObject.get("type");
|
|
||||||
String requestExtraPath = (String) restOptionObject.get("extraPath");
|
|
||||||
url = getUrl(url, requestExtraPath);
|
|
||||||
if (TYPE_VARIABLE_URL_REQUEST.equals(type)) {
|
|
||||||
Pattern p = Pattern.compile("\\{(.*?)\\}");
|
|
||||||
Matcher m = p.matcher(requestExtraPath);
|
|
||||||
List<String> uriVariables = new ArrayList<>();
|
|
||||||
while (m.find()) {
|
|
||||||
String fieldName = m.group(1);
|
|
||||||
uriVariables.add(fieldName);
|
|
||||||
}
|
|
||||||
if (MessageType.JSON.equals(messageType)) {
|
|
||||||
JSONObject jsonObject;
|
|
||||||
if (sendData instanceof JSONObject) {
|
|
||||||
jsonObject = (JSONObject) sendData;
|
|
||||||
} else {
|
|
||||||
jsonObject = (JSONObject) JSONValue.parse((String) sendData);
|
|
||||||
}
|
|
||||||
for (Object tempObject : uriVariables) {
|
|
||||||
String urlVaribleId = (String) tempObject;
|
|
||||||
String uriVariable = (String) jsonObject.get(urlVaribleId);
|
|
||||||
urlVariableList.add(uriVariable);
|
|
||||||
jsonObject.remove(urlVaribleId);
|
|
||||||
}
|
|
||||||
} else if (MessageType.XML.equals(messageType)) {
|
|
||||||
Document doc;
|
|
||||||
if (sendData instanceof Document) {
|
|
||||||
doc = (Document) sendData;
|
|
||||||
} else {
|
|
||||||
doc = convertXmlDocument((String) sendData);
|
|
||||||
}
|
|
||||||
for (Object tempObject : uriVariables) {
|
|
||||||
String urlVaribleId = (String) tempObject;
|
|
||||||
Element element = (Element) doc.selectSingleNode("//" + urlVaribleId);
|
|
||||||
urlVariableList.add(element.getText());
|
|
||||||
if (doc.getRootElement() == element) {
|
|
||||||
doc = null;
|
|
||||||
} else {
|
|
||||||
element.getParent().remove(element);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (urlVariableList.size() > 0) {
|
|
||||||
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
|
|
||||||
Object[] urls = urlVariableList.toArray();
|
|
||||||
url = uriComponents.expand(urls).toUriString();
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] after extand url=[" + url + "] ");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error("Failed to change url", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getUrl(String baseUrl, String extraPath) {
|
|
||||||
if (StringUtils.isBlank(extraPath)) {
|
|
||||||
return baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.contains(extraPath, "http://") || StringUtils.contains(extraPath, "https://")) {
|
|
||||||
return extraPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
String targetUrl = baseUrl;
|
|
||||||
if (!targetUrl.endsWith("/")) {
|
|
||||||
targetUrl += "/";
|
|
||||||
}
|
|
||||||
if (extraPath.startsWith("/")) {
|
|
||||||
targetUrl += extraPath.substring(1);
|
|
||||||
} else {
|
|
||||||
targetUrl += extraPath;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.debug("HttpClientAdapterServiceRest] after concatenate url=[" + targetUrl + "] ");
|
|
||||||
return targetUrl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-71
@@ -1,71 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
public class JsonToSetStatusFilter implements HttpAdapterFilter {
|
|
||||||
private ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
|
||||||
|
|
||||||
int httpStatus = 200;
|
|
||||||
|
|
||||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
|
||||||
try {
|
|
||||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
|
||||||
httpStatus = Integer.parseInt(statusParam);
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
|
||||||
}
|
|
||||||
// HTTP 상태 코드 설정
|
|
||||||
response.setStatus(httpStatus);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
|
||||||
int httpStatus = 200;
|
|
||||||
|
|
||||||
if (rootNode.has("apiRsltCd") && !rootNode.get("apiRsltCd").asText().isEmpty()) {
|
|
||||||
try {
|
|
||||||
String statusParam = rootNode.get("apiRsltCd").asText();
|
|
||||||
httpStatus = Integer.parseInt(statusParam);
|
|
||||||
} catch (NumberFormatException e) {
|
|
||||||
httpStatus = 400; // 잘못된 입력일 경우 400 Bad Request 반환
|
|
||||||
}
|
|
||||||
// HTTP 상태 코드 설정
|
|
||||||
response.setStatus(httpStatus);
|
|
||||||
}
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String orgMessageString;
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
orgMessageString = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
orgMessageString = (String) message;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapper.readTree(orgMessageString);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-110
@@ -1,110 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class JsonToStdConverterFilter implements HttpAdapterFilter {
|
|
||||||
private ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
|
||||||
|
|
||||||
if (rootNode.has("header_part")) {
|
|
||||||
JsonNode headerPart = rootNode.path("header_part");
|
|
||||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
|
||||||
// /api/v1/public/getUserInfo.svc
|
|
||||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
|
||||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
|
||||||
|
|
||||||
// getUserInfo.svc
|
|
||||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
|
||||||
|
|
||||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
|
||||||
if (headerPart instanceof ObjectNode) {
|
|
||||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
|
||||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
|
||||||
if (!headerPart.has("reqRspnsDscd")) {
|
|
||||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
|
||||||
}
|
|
||||||
|
|
||||||
// GUID 강제 설정
|
|
||||||
String orgnlTx = "";
|
|
||||||
if (headerPart.has("orgnlTx") && !headerPart.get("orgnlTx").asText().isEmpty()) {
|
|
||||||
orgnlTx = headerPart.get("orgnlTx").asText();
|
|
||||||
}
|
|
||||||
if (!headerPart.has("tlgrWrtnDt")) {
|
|
||||||
((ObjectNode) headerPart).put("tlgrWrtnDt", orgnlTx);
|
|
||||||
}
|
|
||||||
if (!headerPart.has("tlgrCrtnSysNm")) {
|
|
||||||
((ObjectNode) headerPart).put("tlgrCrtnSysNm", "");
|
|
||||||
}
|
|
||||||
if (!headerPart.has("tlgrSrlNo")) {
|
|
||||||
((ObjectNode) headerPart).put("tlgrSrlNo", "");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
return rootNode.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
|
||||||
|
|
||||||
if (rootNode.has("header_part")) {
|
|
||||||
JsonNode headerPart = rootNode.path("header_part");
|
|
||||||
if (!headerPart.has("eaiIntfId") || headerPart.get("eaiIntfId").asText().isEmpty()) {
|
|
||||||
// /api/v1/public/getUserInfo.svc
|
|
||||||
String inboundUri = prop.getProperty(HttpAdapterServiceKey.INBOUND_EXTURI);
|
|
||||||
String apiPath = prop.getProperty(HttpAdapterServiceKey.API_PATH) + "/";
|
|
||||||
|
|
||||||
// getUserInfo.svc
|
|
||||||
String eaiIntfId = org.apache.commons.lang.StringUtils.removeStart(inboundUri, apiPath);
|
|
||||||
|
|
||||||
// header_part 아래 eaiIntfId가 추가 또는 수정
|
|
||||||
if (headerPart instanceof ObjectNode) {
|
|
||||||
((ObjectNode) headerPart).put("eaiIntfId", eaiIntfId);
|
|
||||||
// 요청 응답 구분코드 강제 설정 -> API명 찾아갈때 필요
|
|
||||||
((ObjectNode) headerPart).put("reqRspnsDscd", "S");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
return rootNode.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String orgMessageString;
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
orgMessageString = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
orgMessageString = (String) message;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapper.readTree(orgMessageString);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-68
@@ -1,68 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class KbankEaiJsonParseFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
private ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
|
||||||
|
|
||||||
ObjectNode replacedJson = mapper.createObjectNode();
|
|
||||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
|
||||||
String fieldName = it.next();
|
|
||||||
String value = rootNode.get(fieldName).asText();
|
|
||||||
JsonNode jsonNode = mapper.readTree(value);
|
|
||||||
replacedJson.set(fieldName, jsonNode);
|
|
||||||
}
|
|
||||||
|
|
||||||
return replacedJson.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, resultMessage);
|
|
||||||
|
|
||||||
ObjectNode replacedJson = mapper.createObjectNode();
|
|
||||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();) {
|
|
||||||
String fieldName = it.next();
|
|
||||||
JsonNode childNode = rootNode.get(fieldName);
|
|
||||||
String childString = mapper.writeValueAsString(childNode);
|
|
||||||
replacedJson.put(fieldName, childString);
|
|
||||||
}
|
|
||||||
|
|
||||||
return replacedJson.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException, JsonProcessingException {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String orgMessageString;
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
orgMessageString = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
orgMessageString = (String) message;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapper.readTree(orgMessageString);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-215
@@ -1,215 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.Enumeration;
|
|
||||||
import java.util.Iterator;
|
|
||||||
import java.text.SimpleDateFormat;
|
|
||||||
|
|
||||||
import javax.crypto.Cipher;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
import javax.crypto.spec.IvParameterSpec;
|
|
||||||
import javax.crypto.Mac;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import org.apache.commons.net.util.Base64;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
|
||||||
import com.eactive.eai.common.server.Keys;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
public class KbankHmacSha256VerifyFilter implements HttpAdapterFilter {
|
|
||||||
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
|
||||||
private static final int TIMESTAMP_EXPIRATION_SECONDS = 60*10*1000;
|
|
||||||
private static final String GROUP_NAME = "HMAC_INFO";
|
|
||||||
|
|
||||||
private ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
|
|
||||||
try {
|
|
||||||
|
|
||||||
String hmacSignature = getHeaderCaseInsensitive(request, "hmac_signature");
|
|
||||||
String hmacTimestamp = getHeaderCaseInsensitive(request, "hmac_timestamp");
|
|
||||||
|
|
||||||
if(StringUtils.isBlank(hmacSignature) || StringUtils.isBlank(hmacTimestamp)) {
|
|
||||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find hmac info");
|
|
||||||
}
|
|
||||||
|
|
||||||
long inputTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(hmacTimestamp).getTime();
|
|
||||||
long currentTime = new Date().getTime();
|
|
||||||
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
|
|
||||||
|
|
||||||
logger.debug("### inputTime :"+inputTime);
|
|
||||||
logger.debug("### currentTime :"+currentTime);
|
|
||||||
logger.debug("### timeStamp :"+timeStamp);
|
|
||||||
|
|
||||||
String systemMode = System.getProperty(Keys.EAI_SYSTEMMODE);
|
|
||||||
|
|
||||||
if(currentTime - inputTime > TIMESTAMP_EXPIRATION_SECONDS) {
|
|
||||||
|
|
||||||
logger.debug("### systemMode:" + systemMode);
|
|
||||||
logger.debug("### currentTime - inputTime:" + (currentTime - inputTime));
|
|
||||||
|
|
||||||
if("P".equals(systemMode)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN,"00"), "Signature verifying failed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String sMessage = (String)message;
|
|
||||||
|
|
||||||
sMessage = sMessage.replace(" ","");
|
|
||||||
sMessage = sMessage.replace("\n","");
|
|
||||||
sMessage = sMessage.replace("\r","");
|
|
||||||
|
|
||||||
sMessage = sMessage + hmacTimestamp;
|
|
||||||
|
|
||||||
logger.info("### sMessage:"+sMessage);
|
|
||||||
|
|
||||||
String alCoId = "AL2021012901001";
|
|
||||||
|
|
||||||
JsonNode rootNode = parseJson(adptGrpName, message);
|
|
||||||
|
|
||||||
for(Iterator<String> it = rootNode.fieldNames(); it.hasNext();){
|
|
||||||
String fieldName = it.next();
|
|
||||||
if(fieldName.equals("ALCO_ID")) alCoId = rootNode.get(fieldName).asText();
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info("### alCoId:"+alCoId);
|
|
||||||
|
|
||||||
Properties hmacProp = PropManager.getInstance().getProperties(GROUP_NAME);
|
|
||||||
|
|
||||||
String hmacKey = hmacProp.getProperty(alCoId+"-hmack-key","");
|
|
||||||
String hmacKek = hmacProp.getProperty(alCoId+"-hmack-kek","");
|
|
||||||
String hmacIvForKey = hmacProp.getProperty(alCoId+"-hmack-iv-for-key","");
|
|
||||||
|
|
||||||
logger.debug("### hmacKey:"+hmacKey);
|
|
||||||
logger.debug("### hmacIvForKey:"+hmacIvForKey);
|
|
||||||
logger.debug("### hmacKek:"+hmacKek);
|
|
||||||
|
|
||||||
//kbank.payment.hmac-key
|
|
||||||
int hmacKeyLen = hmacKey.length();
|
|
||||||
byte[] hmacKeyData = new byte[hmacKeyLen/2];
|
|
||||||
for(int i=0;i<hmacKeyLen;i+=2){
|
|
||||||
hmacKeyData[i/2] = (byte)((Character.digit(hmacKey.charAt(i), 16) << 4) + Character.digit(hmacKey.charAt(i+1), 16));
|
|
||||||
}
|
|
||||||
|
|
||||||
//kbank.payment.hmac-kek
|
|
||||||
int hmacKekLen = hmacKek.length();
|
|
||||||
byte[] hmacKekData = new byte[hmacKekLen/2];
|
|
||||||
for(int i=0;i<hmacKekLen;i+=2){
|
|
||||||
hmacKekData[i/2] = (byte)((Character.digit(hmacKek.charAt(i),16) << 4) + Character.digit(hmacKek.charAt(i+1), 16));
|
|
||||||
}
|
|
||||||
|
|
||||||
//kbank.payment.hmac-iv-for-key
|
|
||||||
int hmacIvForKeyLen = hmacIvForKey.length();
|
|
||||||
byte[] hmacIvForKeyData = new byte[hmacIvForKeyLen/2];
|
|
||||||
for(int i=0;i<hmacIvForKeyLen;i+=2){
|
|
||||||
hmacIvForKeyData[i/2] = (byte)((Character.digit(hmacIvForKey.charAt(i),16) << 4) + Character.digit(hmacIvForKey.charAt(i+1), 16));
|
|
||||||
}
|
|
||||||
|
|
||||||
byte[] decrypedHmacKey = null;
|
|
||||||
|
|
||||||
try{
|
|
||||||
Cipher cp = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
|
||||||
cp.init(Cipher.DECRYPT_MODE, new SecretKeySpec(hmacIvForKeyData,"AES"), new IvParameterSpec(hmacIvForKeyData));
|
|
||||||
decrypedHmacKey = cp.doFinal(hmacKeyData);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
SecretKeySpec secretKey = new SecretKeySpec(decrypedHmacKey, "HmacSHA256");
|
|
||||||
String madeSignature = "";
|
|
||||||
|
|
||||||
logger.info("### secretKey:"+secretKey);
|
|
||||||
|
|
||||||
try{
|
|
||||||
Mac mac = Mac.getInstance("HmacSHA256");
|
|
||||||
mac.init(secretKey);
|
|
||||||
madeSignature= Base64.encodeBase64String(mac.doFinal(sMessage.getBytes()));
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed");
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info("### madeSignature:"+madeSignature);
|
|
||||||
|
|
||||||
if(!StringUtils.equals(hmacSignature, madeSignature)){
|
|
||||||
logger.info("### hmacSignature:"+hmacSignature);
|
|
||||||
logger.info("### madeSignature:"+madeSignature);
|
|
||||||
|
|
||||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed" );
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (JwtAuthException e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Signature verifying failed(Unknown)" );
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info("### pass: "+"success");
|
|
||||||
|
|
||||||
return message;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 대소문자 구분 없이 HTTP 헤더 값을 가져오는 메소드
|
|
||||||
* @param request HTTP 요청 객체
|
|
||||||
* @param headerName 찾고자 하는 헤더 이름
|
|
||||||
* @return 헤더 값 또는 null
|
|
||||||
*/
|
|
||||||
public static String getHeaderCaseInsensitive(HttpServletRequest request, String headerName) {
|
|
||||||
Enumeration<String> headerNames = request.getHeaderNames();
|
|
||||||
while (headerNames.hasMoreElements()) {
|
|
||||||
String header = headerNames.nextElement();
|
|
||||||
if (header != null && header.equalsIgnoreCase(headerName)) {
|
|
||||||
return request.getHeader(header);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public JsonNode parseJson(String adptGrpName, Object message) throws UnsupportedEncodingException, JsonMappingException,JsonProcessingException {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String orgMessageString;
|
|
||||||
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
orgMessageString = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
orgMessageString = (String) message;
|
|
||||||
}
|
|
||||||
|
|
||||||
return mapper.readTree(orgMessageString);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-205
@@ -1,205 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.codec.digest.DigestUtils;
|
|
||||||
import org.apache.commons.codec.digest.HmacAlgorithms;
|
|
||||||
import org.apache.commons.codec.digest.HmacUtils;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.authserver.vo.ClientVO;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
|
|
||||||
public class SnapHmacSha512VerifyFilter implements HttpAdapterFilter {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
|
||||||
private static final int X_TIMESTAMP_EXPIRATION_SECONDS = 60 * 5;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
// @formatter:off
|
|
||||||
/*
|
|
||||||
* HMAC_SHA512 (clientSecret, stringToSign)
|
|
||||||
*
|
|
||||||
* stringToSign = HTTPMethod:EndpointUrl:AccessToken
|
|
||||||
* :Lowercase(HexEncode(SHA-256(minify(RequestBody)))):TimeStamp
|
|
||||||
*/
|
|
||||||
try {
|
|
||||||
String xSignature = request.getHeader("X-SIGNATURE");
|
|
||||||
if (StringUtils.isBlank(xSignature)) {
|
|
||||||
throw new JwtAuthException(String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"), "Can not find X-SIGNATURE");
|
|
||||||
}
|
|
||||||
|
|
||||||
String clientSecret = assignClientSecret(prop, request);
|
|
||||||
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
sb.append(request.getMethod())
|
|
||||||
.append(":")
|
|
||||||
.append(getEndpointUrl(request))
|
|
||||||
.append(":")
|
|
||||||
.append(SnapSimpleOauth2Filter.extractToken(request))
|
|
||||||
.append(":")
|
|
||||||
.append(getRequestBody((String)message))
|
|
||||||
.append(":")
|
|
||||||
.append(getTimeStamp(request));
|
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
if (logger.isDebug()) {
|
|
||||||
logger.debug(sb.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512, clientSecret).hmacHex(sb.toString());
|
|
||||||
|
|
||||||
if (!StringUtils.equals(xSignature, hmac)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Signature verifying failed");
|
|
||||||
}
|
|
||||||
} catch (JwtAuthException e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Signature verifying failed(unkown)");
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignClientSecret(Properties prop, HttpServletRequest request) throws Exception {
|
|
||||||
String clientId = assignClientId(prop, request);
|
|
||||||
if (StringUtils.isBlank(clientId)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Can not find clientId info");
|
|
||||||
}
|
|
||||||
|
|
||||||
ClientVO client = (ClientVO) OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
|
||||||
if (client == null) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Can not find client info");
|
|
||||||
}
|
|
||||||
|
|
||||||
return client.getClientSecret();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignClientId(Properties prop, HttpServletRequest request) {
|
|
||||||
String clientId = null;
|
|
||||||
try {
|
|
||||||
// 이전 filter에서 셋팅한 clientId 확보
|
|
||||||
clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
|
|
||||||
// 이전 filter에서 셋팅한 값이 없다면 header 정보에서 확보
|
|
||||||
if (StringUtils.isBlank(clientId)) {
|
|
||||||
clientId = request.getHeader(HttpAdapterServiceSupport.HEADER_NAME_CLIENT_ID);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return clientId;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getEndpointUrl(HttpServletRequest request) {
|
|
||||||
String servletPath = request.getServletPath();
|
|
||||||
String pathInfo = request.getPathInfo();
|
|
||||||
String queryString = request.getQueryString();
|
|
||||||
|
|
||||||
StringBuilder url = new StringBuilder();
|
|
||||||
url.append(servletPath);
|
|
||||||
|
|
||||||
if (pathInfo != null) {
|
|
||||||
url.append(pathInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (queryString != null) {
|
|
||||||
url.append("?").append(queryString);
|
|
||||||
}
|
|
||||||
|
|
||||||
return url.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getRequestBody(String message) throws Exception {
|
|
||||||
if (StringUtils.isEmpty(message)) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lowercase(HexEncode(SHA-256(minify(RequestBody))))
|
|
||||||
String body = minifyJson(message);
|
|
||||||
try {
|
|
||||||
body = DigestUtils.sha256Hex(body);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"SHA-256 digest error");
|
|
||||||
}
|
|
||||||
return body.toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String minifyJson(String json) {
|
|
||||||
try {
|
|
||||||
ObjectMapper objectMapper = new ObjectMapper();
|
|
||||||
JsonNode jsonNode = objectMapper.readValue(json, JsonNode.class);
|
|
||||||
return jsonNode.toString();
|
|
||||||
} catch (Exception e) {
|
|
||||||
// json이 아닐경우
|
|
||||||
return json;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getTimeStamp(HttpServletRequest request) throws Exception {
|
|
||||||
String timeStamp = request.getHeader("X-TIMESTAMP");
|
|
||||||
if (StringUtils.isBlank(timeStamp)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Can not find X-TIMESTAMP");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2020-12-23T09:10:11+07:00(현재시간이랑 비교로직 추가-보안)
|
|
||||||
ZonedDateTime xTimeStamp = ZonedDateTime.parse(timeStamp, DateTimeFormatter.ISO_DATE_TIME);
|
|
||||||
xTimeStamp = xTimeStamp.plusSeconds(X_TIMESTAMP_EXPIRATION_SECONDS);
|
|
||||||
ZonedDateTime now = ZonedDateTime.now();
|
|
||||||
if (xTimeStamp.isBefore(now.withZoneSameInstant(xTimeStamp.getZone()))) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Too old X-TIMESTAMP");
|
|
||||||
}
|
|
||||||
|
|
||||||
return timeStamp;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String str = "POST:/api/test/aaa/type02/555:"
|
|
||||||
+ "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJzbmFwIl0sImV4cCI6MTY3NjUyNDI1MSwianRpIjoiNzI0MWMyZGUtZjJhNi00NTFmLWExMjQtZGM3NmI0ZGY1OThjIiwiY2xpZW50X2lkIjoic1NHSkR3bEpzZWw1V2VYb2R6ZDNKM01RMjBLWUNacEwifQ.Obe8t8IwuQ3P7i4yCSASYze-9DLmVwXe0g_gBYlwv_Jzc7V8-ooTwp6SVnaNsM6pp1GV-9lxMpAzQO_CRHQq_hdMeiPI_CXHh3gETvjQThn57QGEGdCNp_lUEVYtMPUxi5u3X6Of07o0_OB83WI7rA1zD0DaP8V67pgfq-jMRe_3IXztOYu_nwMgREbGvs9tqcsjxppRKkEHcK1S8Eq4HzaLwjwyHJAhIlTba27yd4T8ELC7IpFphJBfEPF_t0ZpYW15lOrg5pHPjy1xpTV0Kgipog5wycTZlFUeCWWjfxTrpVmt_1XlEOlZH9X6xAefWrH93_fpbt3OcxwP4u9KhA"
|
|
||||||
+ ":424058b889b9d860d13b79d90df52ddcbefba2fc9d27607e999c7c3c4d61d9c8:" + "2023-02-16T09:47:07+07:00";
|
|
||||||
|
|
||||||
String hmac = new HmacUtils(HmacAlgorithms.HMAC_SHA_512,
|
|
||||||
"o3Hre3voTrHbLueDrHC0LYM5effHQZILI8t23htbD12TKD5QJUMONqFqv4494iQS46bzHS0xW1fBC5LHo3D0SzhZvQcPUaJZw0iQ79NnzYFUCTrEsoFJRL300dp3Ql4y")
|
|
||||||
.hmacHex(str);
|
|
||||||
|
|
||||||
// System.out.println(hmac);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-237
@@ -1,237 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.security.KeyFactory;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.security.interfaces.RSAPublicKey;
|
|
||||||
import java.security.spec.InvalidKeySpecException;
|
|
||||||
import java.security.spec.X509EncodedKeySpec;
|
|
||||||
import java.text.ParseException;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.springframework.core.io.ClassPathResource;
|
|
||||||
import org.springframework.core.io.Resource;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthFilter;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.inbound.action.ActionFactory;
|
|
||||||
import com.eactive.eai.inbound.action.RequestAction;
|
|
||||||
import com.eactive.eai.inbound.processor.Processor;
|
|
||||||
import com.eactive.eai.message.StandardMessageUtil;
|
|
||||||
import com.nimbusds.jose.JWSVerifier;
|
|
||||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
|
||||||
import com.nimbusds.jose.util.IOUtils;
|
|
||||||
import com.nimbusds.jwt.SignedJWT;
|
|
||||||
|
|
||||||
public class SnapJwtAuthFilter implements HttpAdapterFilter {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static final String PROP_GROUP_AUTH_SERVER = "OAuthServer";
|
|
||||||
public static final String PROP_KEYSTORE_PATH = "certification.publicKeyPath";
|
|
||||||
|
|
||||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
|
||||||
|
|
||||||
public static final String PAYLOAD_PARAM_NAME_SCOPE = "scope";
|
|
||||||
public static final String PAYLOAD_PARAM_NAME_CLIENT_ID = "client_id";
|
|
||||||
|
|
||||||
private JWSVerifier jwsVerifier;
|
|
||||||
|
|
||||||
public SnapJwtAuthFilter() {
|
|
||||||
super();
|
|
||||||
|
|
||||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(PROP_GROUP_AUTH_SERVER);
|
|
||||||
String publicKeyPath = "/certificate/elink-oauth-dev.pub";
|
|
||||||
if (vo != null) {
|
|
||||||
publicKeyPath = vo.getProperty(PROP_KEYSTORE_PATH);
|
|
||||||
} else {
|
|
||||||
logger.warn("The properties has not been set.[" + PROP_GROUP_AUTH_SERVER + "]");
|
|
||||||
}
|
|
||||||
|
|
||||||
Resource resource = new ClassPathResource(publicKeyPath);
|
|
||||||
String publicKey = null;
|
|
||||||
try {
|
|
||||||
publicKey = IOUtils.readInputStreamToString(resource.getInputStream());
|
|
||||||
publicKey = StringUtils.replace(publicKey, "-----BEGIN PUBLIC KEY-----", "");
|
|
||||||
publicKey = StringUtils.replace(publicKey, "-----END PUBLIC KEY-----", "");
|
|
||||||
publicKey = StringUtils.remove(publicKey, "\r");
|
|
||||||
publicKey = StringUtils.remove(publicKey, "\n");
|
|
||||||
|
|
||||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
|
|
||||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
|
||||||
jwsVerifier = new RSASSAVerifier((RSAPublicKey) keyFactory.generatePublic(keySpec));
|
|
||||||
} catch (final IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
|
||||||
if (StringUtils.isBlank(apiId)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Can not find apiId(apiCode) info");
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
String token = JwtAuthFilter.extractJWTToken(request);
|
|
||||||
SignedJWT signedJWT = SignedJWT.parse(token);
|
|
||||||
|
|
||||||
if (new Date().after(signedJWT.getJWTClaimsSet().getExpirationTime())) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token - expired (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!signedJWT.verify(jwsVerifier)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
|
||||||
if (!verifyScope(scopeSet, signedJWT)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
|
||||||
if (!verifyClientId(prop, signedJWT)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"client_id not matched(header/token)");
|
|
||||||
}
|
|
||||||
} catch (JwtAuthException e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean verifyClientId(Properties prop, SignedJWT signedJWT) {
|
|
||||||
try {
|
|
||||||
// 이전 filter에서 셋팅한 clientId 확보
|
|
||||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
String tokenClientId = (String) signedJWT.getJWTClaimsSet().getClaim(PAYLOAD_PARAM_NAME_CLIENT_ID);
|
|
||||||
|
|
||||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
|
||||||
if (StringUtils.isBlank(headerClientId)) {
|
|
||||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
|
||||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
|
||||||
}
|
|
||||||
} else { // header로 전달된 clientId가 있을때만 비교
|
|
||||||
if (!headerClientId.equals(tokenClientId)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request) {
|
|
||||||
String apiId = null;
|
|
||||||
try {
|
|
||||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
|
||||||
RequestAction action = ActionFactory.createAction(actionName);
|
|
||||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
|
||||||
String[] keys = action.perform(message);
|
|
||||||
apiId = keys[0];
|
|
||||||
|
|
||||||
// PathVariable 지원 추가
|
|
||||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
// // header 에서 확보
|
|
||||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
|
||||||
// if (StringUtils.isBlank(apiId)) {
|
|
||||||
// // url에서 확보
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
|
||||||
// apiId = request.getRequestURI();
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
|
||||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
|
||||||
// // getUserInfo.svc
|
|
||||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
|
||||||
// }
|
|
||||||
|
|
||||||
return apiId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean verifyScope(HashSet<String> scopeSet, SignedJWT signedJWT) throws ParseException {
|
|
||||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
|
||||||
return true; // If no scope is specified in the api, all are allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] scopeArr = signedJWT.getJWTClaimsSet().getStringArrayClaim(PAYLOAD_PARAM_NAME_SCOPE);
|
|
||||||
if (scopeArr == null || scopeArr.length == 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (String scope : scopeArr) {
|
|
||||||
if (scopeSet.contains(scope)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String extractJWTToken(HttpServletRequest request) throws JwtAuthException {
|
|
||||||
String authorization = request.getHeader("Authorization");
|
|
||||||
if (StringUtils.isBlank(authorization)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"No have header info: Authorization");
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] components = authorization.split("\\s");
|
|
||||||
|
|
||||||
if (components.length != 2) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Malformat [Authorization] content");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"[Bearer] is needed");
|
|
||||||
}
|
|
||||||
|
|
||||||
return components[1].trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-205
@@ -1,205 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Set;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.security.core.Authentication;
|
|
||||||
import org.springframework.security.oauth2.common.OAuth2AccessToken;
|
|
||||||
import org.springframework.security.oauth2.provider.OAuth2Authentication;
|
|
||||||
import org.springframework.security.oauth2.provider.token.TokenStore;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.authserver.util.BeanUtils;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.inbound.action.ActionFactory;
|
|
||||||
import com.eactive.eai.inbound.action.RequestAction;
|
|
||||||
import com.eactive.eai.inbound.processor.Processor;
|
|
||||||
import com.eactive.eai.message.StandardMessageUtil;
|
|
||||||
|
|
||||||
public class SnapSimpleOauth2Filter implements HttpAdapterFilter {
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
|
||||||
|
|
||||||
private TokenStore tokenStore;
|
|
||||||
|
|
||||||
public SnapSimpleOauth2Filter() {
|
|
||||||
super();
|
|
||||||
tokenStore = BeanUtils.getBean("tokenStore", TokenStore.class);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
try {
|
|
||||||
String apiId = assignApiId(adptGrpName, adptName, message, prop, request);
|
|
||||||
if (StringUtils.isBlank(apiId)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Can not find apiId(apiCode) info");
|
|
||||||
}
|
|
||||||
|
|
||||||
String tokenStr = extractToken(request);
|
|
||||||
|
|
||||||
OAuth2AccessToken token = tokenStore.readAccessToken(tokenStr);
|
|
||||||
if (token == null) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "03"),
|
|
||||||
"Token Not Found (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (token.isExpired()) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token - expired (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
OAuth2Authentication authentication = tokenStore.readAuthentication(token);
|
|
||||||
if (!authentication.isAuthenticated()) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
// check scope
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
HashSet<String> scopeSet = manager.getApiScopeMap().get(apiId);
|
|
||||||
if (!verifyScope(scopeSet, authentication)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
String.format("Insufficient [Scope](Allowed Scope=%s)", scopeSet.toString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
// header 값으로 전송된 clientId와 토큰 소유 clientId check
|
|
||||||
if (!verifyClientId(prop, authentication)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"client_id not matched(header/token)");
|
|
||||||
}
|
|
||||||
} catch (JwtAuthException e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "01"),
|
|
||||||
"Invalid Token (B2B)");
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean verifyScope(HashSet<String> scopeSet, OAuth2Authentication auth) {
|
|
||||||
if (scopeSet == null || scopeSet.isEmpty()) {
|
|
||||||
return true; // If no scope is specified in the api, all are allowed
|
|
||||||
}
|
|
||||||
|
|
||||||
Set<String> scopesInToken = auth.getOAuth2Request().getScope();
|
|
||||||
|
|
||||||
if (scopesInToken == null || scopesInToken.isEmpty()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (String scope : scopesInToken) {
|
|
||||||
if (scopeSet.contains(scope)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean verifyClientId(Properties prop, Authentication authentication) {
|
|
||||||
try {
|
|
||||||
// 이전 filter에서 셋팅한 clientId 확보
|
|
||||||
String headerClientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
String tokenClientId = ((OAuth2Authentication) authentication).getOAuth2Request().getClientId();
|
|
||||||
|
|
||||||
// 이전 filter에서 셋팅한 값이 없다면 token 정보에서 확보
|
|
||||||
if (StringUtils.isBlank(headerClientId)) {
|
|
||||||
if (StringUtils.isNotBlank(tokenClientId)) {
|
|
||||||
prop.put(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID, tokenClientId);
|
|
||||||
}
|
|
||||||
} else { // header로 전달된 clientId가 있을때만 비교
|
|
||||||
if (!headerClientId.equals(tokenClientId)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignApiId(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request) {
|
|
||||||
String apiId = null;
|
|
||||||
try {
|
|
||||||
String actionName = prop.getProperty(Processor.REQUEST_ACTION);
|
|
||||||
RequestAction action = ActionFactory.createAction(actionName);
|
|
||||||
action.setAdapterInfo(adptGrpName, adptName, prop);
|
|
||||||
String[] keys = action.perform(message);
|
|
||||||
apiId = keys[0];
|
|
||||||
|
|
||||||
// PathVariable 지원 추가
|
|
||||||
apiId = StandardMessageUtil.getMatchedKey(apiId, actionName);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
// // header 에서 확보
|
|
||||||
// String apiId = request.getHeader(HEADER_NAME_API_CODE);
|
|
||||||
// if (StringUtils.isBlank(apiId)) {
|
|
||||||
// // url에서 확보
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc/
|
|
||||||
// apiId = request.getRequestURI();
|
|
||||||
// // /ONLWeb/api/v1/public/getUserInfo.svc
|
|
||||||
// apiId = StringUtils.removeEnd(apiId, "/");
|
|
||||||
// // getUserInfo.svc
|
|
||||||
// apiId = StringUtils.substringAfterLast(apiId, "/");
|
|
||||||
// }
|
|
||||||
|
|
||||||
return apiId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String extractToken(HttpServletRequest request) throws JwtAuthException {
|
|
||||||
String authorization = request.getHeader("Authorization");
|
|
||||||
if (StringUtils.isBlank(authorization)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"No have header info: Authorization");
|
|
||||||
}
|
|
||||||
|
|
||||||
String[] components = authorization.split("\\s");
|
|
||||||
|
|
||||||
if (components.length != 2) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"Malformat [Authorization] content");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.equalsIgnoreCase(components[0], "Bearer")) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.format("%d%s%s", HttpStatus.UNAUTHORIZED.value(), SERVICE_CODE_UNKNOWN, "00"),
|
|
||||||
"[Bearer] is needed");
|
|
||||||
}
|
|
||||||
|
|
||||||
return components[1].trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
-120
@@ -1,120 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.AdapterManager;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.authserver.vo.ClientVO;
|
|
||||||
import com.eactive.eai.common.dao.DAOException;
|
|
||||||
import com.eactive.eai.common.property.PropGroupVO;
|
|
||||||
import com.eactive.eai.common.property.PropManager;
|
|
||||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountBatchUtil;
|
|
||||||
import com.eactive.eai.custom.adapter.http.util.VirtualAccountTransform;
|
|
||||||
|
|
||||||
public class VirtualAccountCryptoFilter implements HttpAdapterFilter {
|
|
||||||
// FIXME : kbank - 프라퍼티 그릅정의 확정
|
|
||||||
private static final String BATCH_CHECK_URL = "/batch/";
|
|
||||||
private static final String BATCH_PROP_GROUP = "VIRTUALACCOUNT_INFO";
|
|
||||||
private static final String BATCH_FILE_PATH = "BATCH_FILE_PATH";
|
|
||||||
private static final String FILE_NAME_PATTERN = "FILE_NAME_PATTERN";
|
|
||||||
|
|
||||||
private String getAesKey(String clientId) {
|
|
||||||
OAuth2Manager manager = OAuth2Manager.getInstance();
|
|
||||||
try {
|
|
||||||
ClientVO client = manager.getClientInfo(clientId);
|
|
||||||
return client.getSecurityKey();
|
|
||||||
} catch (DAOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isBatch(HttpServletRequest request) {
|
|
||||||
String uri = request.getRequestURI();
|
|
||||||
return uri != null && uri.contains(BATCH_CHECK_URL);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getRootFilePath() {
|
|
||||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(BATCH_PROP_GROUP);
|
|
||||||
return vo.getProperty(BATCH_FILE_PATH);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getFileNamePattern() {
|
|
||||||
PropGroupVO vo = PropManager.getInstance().getPropGroupVO(BATCH_PROP_GROUP);
|
|
||||||
return vo.getProperty(FILE_NAME_PATTERN);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String encPaths = prop.getProperty(HttpAdapterServiceKey.ENC_PATHS);
|
|
||||||
List<String> encFieldList = null;
|
|
||||||
String clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
String aesKey = getAesKey(clientId);
|
|
||||||
|
|
||||||
String convertedMessage = null;
|
|
||||||
if(isBatch(request)) {
|
|
||||||
String rootFilePath = getRootFilePath();
|
|
||||||
String fileNamePattern = getFileNamePattern();
|
|
||||||
VirtualAccountBatchUtil batchUtil = new VirtualAccountBatchUtil();
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
convertedMessage = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
convertedMessage = (String) message;
|
|
||||||
}
|
|
||||||
batchUtil.unzipAndSave(aesKey, convertedMessage, rootFilePath, fileNamePattern);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if(StringUtils.isNotBlank(encPaths)) {
|
|
||||||
String[] items = encPaths.split(",");
|
|
||||||
encFieldList = Arrays.asList(items);
|
|
||||||
if(message instanceof byte[]) {
|
|
||||||
convertedMessage = new String((byte[])message, charset);
|
|
||||||
} else {
|
|
||||||
convertedMessage = (String) message;
|
|
||||||
}
|
|
||||||
convertedMessage = VirtualAccountTransform.toCubeOne(aesKey, encFieldList, convertedMessage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return convertedMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
String charset = StringUtils.defaultIfBlank(AdapterManager.getInstance().getAdapterGroupVO(adptGrpName).getMessageEncode(), "UTF-8");
|
|
||||||
String encPaths = prop.getProperty(HttpAdapterServiceKey.ENC_PATHS);
|
|
||||||
List<String> encFieldList = null;
|
|
||||||
String clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
String aesKey = getAesKey(clientId);
|
|
||||||
|
|
||||||
if(isBatch(request)) {
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
String resMessageString = null;
|
|
||||||
if(StringUtils.isNotBlank(encPaths)) {
|
|
||||||
String[] items = encPaths.split(",");
|
|
||||||
encFieldList = Arrays.asList(items);
|
|
||||||
if(resultMessage instanceof byte[]) {
|
|
||||||
resMessageString = new String((byte[])resultMessage, charset);
|
|
||||||
} else {
|
|
||||||
resMessageString = (String) resultMessage;
|
|
||||||
}
|
|
||||||
resMessageString = VirtualAccountTransform.toAES(aesKey, encFieldList, resMessageString);
|
|
||||||
}
|
|
||||||
return resMessageString;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import com.eactive.eai.util.TestModeChecker;
|
|
||||||
|
|
||||||
import com.cubeone.CubeOneAPI;
|
|
||||||
|
|
||||||
public class CubeOneCryptoUtil {
|
|
||||||
private static boolean testMode = TestModeChecker.isTestMode();
|
|
||||||
|
|
||||||
public static String encryptPI(String plainText) throws Exception {
|
|
||||||
// FIXME : kbank - kbank내애서는 testMode 체크 제거 검토
|
|
||||||
if (testMode) {
|
|
||||||
return plainText;
|
|
||||||
} else {
|
|
||||||
String encryptedText = null;
|
|
||||||
byte errbyte[] = new byte[5];
|
|
||||||
byte[] inbyte;
|
|
||||||
try {
|
|
||||||
inbyte = plainText.getBytes();
|
|
||||||
encryptedText = CubeOneAPI.coencbytes(inbyte, inbyte.length, "AES_PI", 11, null, null, errbyte);
|
|
||||||
} catch (UnsatisfiedLinkError e) {
|
|
||||||
throw new Exception("encryptPI error - ", e);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new Exception("encryptPI error - ", e);
|
|
||||||
}
|
|
||||||
//
|
|
||||||
|
|
||||||
if (errbyte[0] != 48) {
|
|
||||||
throw new Exception("encryptPI error - " + new String(errbyte));
|
|
||||||
}
|
|
||||||
return encryptedText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String decryptPI(String encryptedText) throws Exception {
|
|
||||||
// FIXME : kbank - kbank내애서는 testMode 체크 제거 검토
|
|
||||||
if (testMode) {
|
|
||||||
return encryptedText;
|
|
||||||
} else {
|
|
||||||
String decryptedText = null;
|
|
||||||
byte errbyte[] = new byte[5];
|
|
||||||
byte[] decbyte;
|
|
||||||
decbyte = CubeOneAPI.codecbyte(encryptedText, "AES_PI", 11, null, null, errbyte);
|
|
||||||
if (decbyte != null) {
|
|
||||||
decryptedText = new String(decbyte);
|
|
||||||
}
|
|
||||||
if (errbyte[0] != 48) {
|
|
||||||
throw new Exception("decryptPI error - " + new String(errbyte));
|
|
||||||
}
|
|
||||||
return decryptedText;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import java.io.ByteArrayInputStream;
|
|
||||||
import java.io.ByteArrayOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Base64;
|
|
||||||
import java.util.zip.GZIPInputStream;
|
|
||||||
import java.util.zip.GZIPOutputStream;
|
|
||||||
|
|
||||||
public class GzipBase64Util {
|
|
||||||
|
|
||||||
private static final String DEFAULT_CAHRSET = "UTF-8";
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String originalString = "압축하고 인코딩할 문자열입니다.";
|
|
||||||
|
|
||||||
try {
|
|
||||||
String base64EncodedData = compress(originalString);
|
|
||||||
|
|
||||||
// System.out.println("Original String: " + originalString);
|
|
||||||
// System.out.println("Base64 Encoded String: " + base64EncodedData);
|
|
||||||
|
|
||||||
// Base64 디코딩 후 gzip 압축 해제
|
|
||||||
String decodedString = decompress(base64EncodedData);
|
|
||||||
|
|
||||||
// System.out.println("Decoded String: " + decodedString);
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String compress(String plainText) throws IOException {
|
|
||||||
if (plainText == null || plainText.isEmpty()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
|
||||||
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
|
|
||||||
gzipOutputStream.write(plainText.getBytes(DEFAULT_CAHRSET));
|
|
||||||
}
|
|
||||||
byte[] compressedData = byteArrayOutputStream.toByteArray();
|
|
||||||
return Base64.getEncoder().encodeToString(compressedData);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String decompress(String base64EncodedData) throws IOException {
|
|
||||||
|
|
||||||
if (base64EncodedData == null || base64EncodedData.length() == 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
byte[] compressedData = Base64.getDecoder().decode(base64EncodedData);
|
|
||||||
|
|
||||||
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
|
|
||||||
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(compressedData);
|
|
||||||
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream)) {
|
|
||||||
|
|
||||||
byte[] buffer = new byte[1024];
|
|
||||||
int len;
|
|
||||||
while ((len = gzipInputStream.read(buffer)) > 0) {
|
|
||||||
byteArrayOutputStream.write(buffer, 0, len);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return byteArrayOutputStream.toString(DEFAULT_CAHRSET);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.eactive.eai.util.CryptoUtil;
|
|
||||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
|
||||||
|
|
||||||
public class ToAesTransformer implements ValueTransformer<String, String> {
|
|
||||||
public static final String AESKEY = "AESKEY";
|
|
||||||
public static final String PLAIN_VALUE = "PLAIN_VALUE";
|
|
||||||
private final Map<String, Object> properties = new HashMap<>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setProperty(String propertyName, Object value) {
|
|
||||||
properties.put(propertyName, value);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String getProperty(String propertyName) {
|
|
||||||
return (String)properties.get(propertyName);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String transform(String value) throws Exception {
|
|
||||||
String apiKey = (String) properties.get(ToAesTransformer.AESKEY);
|
|
||||||
String text = CubeOneCryptoUtil.decryptPI(value);
|
|
||||||
properties.put(PLAIN_VALUE, text);
|
|
||||||
return CryptoUtil.encryptAES(apiKey, text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.eactive.eai.util.CryptoUtil;
|
|
||||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
|
||||||
|
|
||||||
public class ToCubeOneTransformer implements ValueTransformer<String, String> {
|
|
||||||
public static final String AESKEY = "AESKEY";
|
|
||||||
public static final String PLAIN_VALUE = "PLAIN_VALUE";
|
|
||||||
private final Map<String, Object> properties = new HashMap<>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void setProperty(String propertyName, Object value) {
|
|
||||||
properties.put(propertyName, value);
|
|
||||||
}
|
|
||||||
@Override
|
|
||||||
public String getProperty(String propertyName) {
|
|
||||||
return (String)properties.get(propertyName);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String transform(String value) throws Exception {
|
|
||||||
String apiKey = (String) properties.get(ToCubeOneTransformer.AESKEY);
|
|
||||||
String text = CryptoUtil.decryptAES(apiKey, value);
|
|
||||||
properties.put(PLAIN_VALUE, text);
|
|
||||||
return CubeOneCryptoUtil.encryptPI(text);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.nio.file.StandardOpenOption;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.time.ZonedDateTime;
|
|
||||||
import java.time.format.DateTimeFormatter;
|
|
||||||
import java.util.regex.Matcher;
|
|
||||||
import java.util.regex.Pattern;
|
|
||||||
|
|
||||||
import com.eactive.eai.util.CryptoUtil;
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
|
||||||
|
|
||||||
public class VirtualAccountBatchUtil {
|
|
||||||
private ObjectMapper mapper = new ObjectMapper();
|
|
||||||
|
|
||||||
public String getGzipValue(String jsonString, String path) {
|
|
||||||
try {
|
|
||||||
JsonNode rootNode = mapper.readTree(jsonString);
|
|
||||||
JsonNode childNode = rootNode.get(path);
|
|
||||||
String gzippedValue = childNode.asText();
|
|
||||||
return gzippedValue;
|
|
||||||
}
|
|
||||||
catch(Exception ex) {
|
|
||||||
ex.printStackTrace();
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AZZ22-%d{yyyyMMdd}-%d{hhmmss}.enc -> AZZ22-20240924-093257.enc
|
|
||||||
public static String updateDatePattern(String patterm) {
|
|
||||||
String str[] = patterm.split("%d");
|
|
||||||
String converted = "";
|
|
||||||
for(int i=0; i<str.length; i++){
|
|
||||||
if(i<1){
|
|
||||||
converted = str[i];
|
|
||||||
}else{
|
|
||||||
String newMsg = "%d"+str[i];
|
|
||||||
Matcher matcher = Pattern.compile("%d\\{([a-zA-Z \\-]+)\\}").matcher(newMsg);
|
|
||||||
if (matcher.find()) {
|
|
||||||
String datePattern = matcher.group(1);
|
|
||||||
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(datePattern);
|
|
||||||
converted = converted + newMsg.replaceAll("%d\\{([a-zA-Z \\-]+)\\}", dateFormat.format(ZonedDateTime.now()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return converted;
|
|
||||||
}
|
|
||||||
|
|
||||||
// FIXME : kbank - 배치 파일명 생성 규칙에 따라 수정
|
|
||||||
public String unzipAndSave(String aesKey, String jsonString, String rootFilePath, String fileNamePattern) throws Exception {
|
|
||||||
// gzippedValue 추출
|
|
||||||
String gzippedValue = getGzipValue(jsonString, "encData");
|
|
||||||
// System.out.println("gzippedValue[" + gzippedValue + "]");
|
|
||||||
|
|
||||||
// 압축 해제
|
|
||||||
String unziped = GzipBase64Util.decompress(gzippedValue);
|
|
||||||
// AES 복호화
|
|
||||||
String text = CryptoUtil.decryptAES(aesKey, unziped);
|
|
||||||
|
|
||||||
// 현재 처리 시각을 기반으로 파일명 생성
|
|
||||||
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
|
|
||||||
// String fileName = LocalDateTime.now().format(formatter) + ".txt";
|
|
||||||
|
|
||||||
String fileName = updateDatePattern(fileNamePattern);
|
|
||||||
// TODO : Add additional pattern logic
|
|
||||||
|
|
||||||
String filePath = Paths.get(rootFilePath, fileName).toString();
|
|
||||||
|
|
||||||
Files.write(Paths.get(filePath), text.getBytes(), StandardOpenOption.CREATE);
|
|
||||||
|
|
||||||
// 결과 JSON 구성
|
|
||||||
ObjectNode replacedJson = mapper.createObjectNode();
|
|
||||||
replacedJson.put("filePath", filePath);
|
|
||||||
replacedJson.put("fileName", fileName);
|
|
||||||
return replacedJson.toString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package com.eactive.eai.custom.adapter.http.util;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
import com.eactive.eai.util.json.JsonPathsTransform;
|
|
||||||
import com.eactive.eai.util.json.transformer.ValueTransformer;
|
|
||||||
|
|
||||||
public class VirtualAccountTransform {
|
|
||||||
protected static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
public static String toAES(String aesKey, List<String> encFieldPaths, String message) {
|
|
||||||
ToAesTransformer encTramsformer = new ToAesTransformer();
|
|
||||||
encTramsformer.setProperty("AESKEY", aesKey);
|
|
||||||
|
|
||||||
Map<String, ValueTransformer<String, String>> pathTransformerMap = new HashMap<>();
|
|
||||||
for (String path : encFieldPaths) {
|
|
||||||
pathTransformerMap.put(path.trim(), encTramsformer);
|
|
||||||
}
|
|
||||||
String modifiedJsonString = JsonPathsTransform.modifyValuesAtPaths(message, pathTransformerMap, false);
|
|
||||||
|
|
||||||
return modifiedJsonString;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static byte[] toCubeOne(String aesKey, List<String> encFieldPaths, byte[] messageBytes) {
|
|
||||||
String defaultCharset = "utf-8";
|
|
||||||
try {
|
|
||||||
String message = new String(messageBytes, defaultCharset);
|
|
||||||
String retMessage = toCubeOne(aesKey, encFieldPaths, message);
|
|
||||||
return retMessage.getBytes(defaultCharset);
|
|
||||||
} catch (UnsupportedEncodingException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return messageBytes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String toCubeOne(String aesKey, List<String> encFieldPaths, String message) {
|
|
||||||
ToCubeOneTransformer encTramsformer = new ToCubeOneTransformer();
|
|
||||||
|
|
||||||
if(logger.isDebug()) {
|
|
||||||
logger.debug("AESKEY=" + aesKey);
|
|
||||||
}
|
|
||||||
encTramsformer.setProperty("AESKEY", aesKey);
|
|
||||||
|
|
||||||
Map<String, ValueTransformer<String, String>> pathTransformerMap = new HashMap<>();
|
|
||||||
for (String path : encFieldPaths) {
|
|
||||||
pathTransformerMap.put(path.trim(), encTramsformer);
|
|
||||||
}
|
|
||||||
String modifiedJsonString = JsonPathsTransform.modifyValuesAtPaths(message, pathTransformerMap, false);
|
|
||||||
|
|
||||||
return modifiedJsonString;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
String aesKey = "ONAuROzlqWB4VuBwO5C/FA==";
|
|
||||||
String text = "Hello AES 한글";
|
|
||||||
String encText = "3hQyg4xrUrFQt09XKLkmutQ4pZyuKc242LGQ1dyDMTg=";
|
|
||||||
String json = "{\"encAccount\":\"3hQyg4xrUrFQt09XKLkmutQ4pZyuKc242LGQ1dyDMTg=\"}";
|
|
||||||
List<String> list = new ArrayList<>();
|
|
||||||
list.add(" $.encAccount ");
|
|
||||||
list.add(" $.accounts$.encAccount ");
|
|
||||||
String cubeOneJson = toCubeOne(aesKey, list, json);
|
|
||||||
// System.out.println(cubeOneJson);
|
|
||||||
// System.out.println(toAES(aesKey, list, cubeOneJson));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-152
@@ -1,152 +0,0 @@
|
|||||||
package com.eactive.eai.custom.kjb.adapter.http.dynamic.filter;
|
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.security.InvalidKeyException;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import javax.crypto.Mac;
|
|
||||||
import javax.crypto.spec.SecretKeySpec;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
import javax.servlet.http.HttpServletResponse;
|
|
||||||
|
|
||||||
import org.apache.commons.net.util.Base64;
|
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceSupport;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.HttpAdapterFilter;
|
|
||||||
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
|
|
||||||
import com.eactive.eai.authserver.service.OAuth2Manager;
|
|
||||||
import com.eactive.eai.authserver.vo.ClientVO;
|
|
||||||
import com.eactive.eai.common.util.Logger;
|
|
||||||
|
|
||||||
public class KjbHmacSha256VerifyFilter implements HttpAdapterFilter, HttpAdapterServiceKey {
|
|
||||||
|
|
||||||
static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);
|
|
||||||
|
|
||||||
private static final String SERVICE_CODE_UNKNOWN = "00";
|
|
||||||
|
|
||||||
public KjbHmacSha256VerifyFilter() {
|
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPreFilter(String adptGrpName, String adptName, Object message, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
|
|
||||||
String inboundMethod = prop.getProperty(INBOUND_METHOD);
|
|
||||||
String inboundUri = prop.getProperty(INBOUND_URI);
|
|
||||||
String inboundBody = prop.getProperty(INBOUND_REQUEST_MESSAGE);
|
|
||||||
|
|
||||||
try {
|
|
||||||
String xObpPartnercode = request.getHeader("x-obp-partnercode");
|
|
||||||
String xObpSignatureUrl = request.getHeader("x-obp-signature-url");
|
|
||||||
String xObpSignatureBody = request.getHeader("x-obp-signature-body");
|
|
||||||
if (StringUtils.isBlank(xObpPartnercode)
|
|
||||||
|| StringUtils.isBlank(xObpSignatureUrl)
|
|
||||||
|| StringUtils.isBlank(xObpSignatureBody)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Can not find mandatory Http Header");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (StringUtils.isNotBlank(prop.getProperty(INBOUND_QUERY_STRING))) {
|
|
||||||
inboundUri = inboundUri + "?" + prop.getProperty(INBOUND_QUERY_STRING);
|
|
||||||
inboundBody = "";
|
|
||||||
}
|
|
||||||
String chkUrl = inboundMethod + "&" + inboundUri;
|
|
||||||
String chkBody = inboundBody;
|
|
||||||
String clientSecret = assignClientSecret(prop, request);
|
|
||||||
|
|
||||||
String macUrl = calculateHMAC(chkUrl, clientSecret);
|
|
||||||
String macBody = calculateHMAC(chkBody, clientSecret);
|
|
||||||
|
|
||||||
if (!StringUtils.equals(xObpSignatureUrl, macUrl)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Signature verifying failed : x-obp-signature-url");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!StringUtils.equals(xObpSignatureBody, macBody)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Signature verifying failed : x-obp-signature-body");
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (JwtAuthException e) {
|
|
||||||
logger.debug(e.getMessage());
|
|
||||||
throw e;
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Signature verifying failed(unkown)");
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String calculateHMAC(String data, String key)
|
|
||||||
throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
|
|
||||||
|
|
||||||
Mac mac = Mac.getInstance("HmacSHA256");
|
|
||||||
mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
|
|
||||||
return Base64.encodeBase64String(mac.doFinal(data.getBytes("UTF-8")));
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignClientSecret(Properties prop, HttpServletRequest request) throws Exception {
|
|
||||||
String clientId = assignClientId(prop, request);
|
|
||||||
if (StringUtils.isBlank(clientId)) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Can not find clientId info");
|
|
||||||
}
|
|
||||||
|
|
||||||
ClientVO client = (ClientVO) OAuth2Manager.getInstance().getClientDeatilsStore().get(clientId);
|
|
||||||
if (client == null) {
|
|
||||||
throw new JwtAuthException(
|
|
||||||
String.valueOf(HttpStatus.UNAUTHORIZED.value()),
|
|
||||||
"Can not find client info");
|
|
||||||
}
|
|
||||||
|
|
||||||
return client.getClientSecret();
|
|
||||||
}
|
|
||||||
|
|
||||||
private String assignClientId(Properties prop, HttpServletRequest request) {
|
|
||||||
String clientId = null;
|
|
||||||
try {
|
|
||||||
// 이전 filter에서 셋팅한 clientId 확보
|
|
||||||
clientId = prop.getProperty(HttpAdapterServiceSupport.PROPERTIES_NAME_CLIENT_ID);
|
|
||||||
|
|
||||||
// 이전 filter에서 셋팅한 값이 없다면 header 정보에서 확보
|
|
||||||
if (StringUtils.isBlank(clientId)) {
|
|
||||||
clientId = request.getHeader(HttpAdapterServiceSupport.HEADER_NAME_CLIENT_ID);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return clientId;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Object doPostFilter(String adptGrpName, String adptName, Object resultMessage, Properties prop,
|
|
||||||
HttpServletRequest request, HttpServletResponse response) throws Exception {
|
|
||||||
|
|
||||||
String outboundBody = (String) resultMessage;
|
|
||||||
|
|
||||||
try {
|
|
||||||
String clientSecret = assignClientSecret(prop, request);
|
|
||||||
String macBody = calculateHMAC(outboundBody, clientSecret);
|
|
||||||
|
|
||||||
response.addHeader("x-obp-signature-body", macBody);
|
|
||||||
} catch (Exception e) {
|
|
||||||
logger.error(e.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return resultMessage;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.message.StandardItem;
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.filter.MessageFilter;
|
|
||||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
|
||||||
import com.eactive.eai.message.service.InterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class FlatMessageFilterKAKAOCARD implements MessageFilter {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public StandardMessage doFilter(StandardMessage message) {
|
|
||||||
|
|
||||||
// 카카오은행 기준
|
|
||||||
// 전체길이(8) : 전체길이포함 전체
|
|
||||||
// 헤더 : 150
|
|
||||||
// 공통부: 850
|
|
||||||
// DATA헤더 : 10
|
|
||||||
// DATA : ?
|
|
||||||
// 종료 : @@ : 2
|
|
||||||
// 예) DATA가 320byte이면 전체길이는 1332 임
|
|
||||||
|
|
||||||
// 요청시 MESSAGE 부가 없음
|
|
||||||
// 응답시 MESSAGE 부가 있음
|
|
||||||
|
|
||||||
boolean isMessageHidden = true;
|
|
||||||
// 아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
|
||||||
StandardItem mesgDmanDvcd = message.findItem("Header.MESG_DMAN_DVCD");
|
|
||||||
if (mesgDmanDvcd != null && StringUtils.equals(mesgDmanDvcd.getValue(), "R")) {
|
|
||||||
isMessageHidden = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// message부 보이기 여부
|
|
||||||
StandardItem msg = message.findItem("MSG");
|
|
||||||
// 아래로직은 표준전문에서 요청일때 MESSAGE부가 안보이고 응답일때 MESSAGE부 보이게 설정
|
|
||||||
msg.setHidden(isMessageHidden);
|
|
||||||
|
|
||||||
int totalSize = 0; // 전체 길이 ( 메시지여부에 따라 변경됨)
|
|
||||||
int ioSize = 0; // 데이터부 길이
|
|
||||||
int messageSize = 0; // 메시지부 길이
|
|
||||||
|
|
||||||
try {
|
|
||||||
ioSize = message.getBizDataBytes().length;
|
|
||||||
// 데이터부 길이 설정
|
|
||||||
StandardItem dataHedrLen = message.findItem("DataPart.DataHeader.DATA_HEDR_LEN");
|
|
||||||
dataHedrLen.setValue(String.valueOf(ioSize));
|
|
||||||
} catch (Exception e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
messageSize = message.getBytesDataLengthForPath("MSG");
|
|
||||||
if (messageSize > 10) {
|
|
||||||
StandardItem msgLen = message.findItem("MSG.MSG_HEDR_LEN");
|
|
||||||
msgLen.setValue(String.valueOf(messageSize - 10));
|
|
||||||
}
|
|
||||||
StandardItem msgCnt = message.findItem("MSG.OUTPUT_MSG_NCNT");
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isMessageHidden) {
|
|
||||||
// 전체길이 = 150 + 850 + 메시지부길이(X) + DATA부(10) + bizData(?) +종료부(2)
|
|
||||||
totalSize = 150 + 850 + 0 + 10 + ioSize + 2;
|
|
||||||
} else {
|
|
||||||
// 전체길이 = 150 + 850 + 메시지부길이(배열존재(출력메시지개수)) + DATA부(10) + bizData +종료부(2)
|
|
||||||
totalSize = 150 + 850 + messageSize + 10 + ioSize + 2;
|
|
||||||
}
|
|
||||||
// 전체 길이 셋팅
|
|
||||||
try {
|
|
||||||
message.setLlData(String.valueOf(totalSize));
|
|
||||||
} catch (Exception e) {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
package com.eactive.eai.custom.message;
|
|
||||||
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
|
||||||
|
|
||||||
import com.eactive.eai.message.StandardItem;
|
|
||||||
import com.eactive.eai.message.StandardMessage;
|
|
||||||
import com.eactive.eai.message.filter.MessageFilter;
|
|
||||||
import com.eactive.eai.message.manager.StandardMessageManager;
|
|
||||||
import com.eactive.eai.message.service.InterfaceMapper;
|
|
||||||
import com.ext.eai.common.stdmessage.STDMessageKeys;
|
|
||||||
|
|
||||||
@SuppressWarnings("serial")
|
|
||||||
public class FlatMessageFilterSBI implements MessageFilter {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public StandardMessage doFilter(StandardMessage message) {
|
|
||||||
// total 메시지 길이 설정
|
|
||||||
int totalSize = 0;
|
|
||||||
try {
|
|
||||||
totalSize = message.getBytesDataLength();
|
|
||||||
message.setLlData(String.valueOf(totalSize));
|
|
||||||
} catch (Exception e) {
|
|
||||||
}
|
|
||||||
|
|
||||||
// whlMesgLen=전체길이 - 채널헤더길이(24) - ZZ(2)
|
|
||||||
try {
|
|
||||||
StandardItem whlMesgLenItem = message.findItem("STD_HEADER.whlMesgLen");
|
|
||||||
if (whlMesgLenItem != null) {
|
|
||||||
int whlMesgLen = totalSize - 24 - 2;
|
|
||||||
whlMesgLenItem.setValue(String.valueOf(whlMesgLen));
|
|
||||||
}
|
|
||||||
|
|
||||||
// stndHdrLen=전체길이 - 채널헤더길이(24) - bizData길이 - ZZ(2)
|
|
||||||
StandardItem stndHdrLenItem = message.findItem("STD_HEADER.stndHdrLen");
|
|
||||||
if (stndHdrLenItem != null) {
|
|
||||||
int stndHdrLen = totalSize - 24 - message.getBizDataBytes().length - 2;
|
|
||||||
stndHdrLenItem.setValue(String.valueOf(stndHdrLen));
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
}
|
|
||||||
|
|
||||||
// STD_HEADER.rsltCd 설정
|
|
||||||
StandardMessageManager standardManager = StandardMessageManager.getInstance();
|
|
||||||
InterfaceMapper mapper = standardManager.getMapper();
|
|
||||||
if (StringUtils.equals(mapper.getSendRecvDivision(message), "R")) {
|
|
||||||
StandardItem rsltCdItem = message.findItem("STD_HEADER.rsltCd");
|
|
||||||
if (StringUtils.equals(mapper.getResponseType(message), STDMessageKeys.RESPONSE_TYPE_CODE_N)) {
|
|
||||||
rsltCdItem.setValue("00"); // STD_MSG_RSLT_CD_SUCCESS
|
|
||||||
} else {
|
|
||||||
rsltCdItem.setValue("99"); // STD_MSG_RSLT_CD_ERROR_UNKNOWN
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user