删除冗余debug信息,优化三方认证/解密代码容错性

This commit is contained in:
zz 2021-12-02 14:59:32 +08:00
parent 318ebf37b0
commit b332702b8b
6 changed files with 73 additions and 78 deletions

View File

@ -48,13 +48,13 @@ public class QueryStopChargeController {
//判断三方的订单号是否存在 //判断三方的订单号是否存在
EtOrderMapping etOrderMapping = etOrderMappingRepo.findByEvcsOrderNo(startChargeSeq).orElse(null); EtOrderMapping etOrderMapping = etOrderMappingRepo.findByEvcsOrderNo(startChargeSeq).orElse(null);
if (etOrderMapping == null) { if (etOrderMapping == null) {
return failCommonResponse(queryStopChargeResponse); return failCommonResponse(queryStopChargeResponse, "错误的充电订单号");
} }
String xhOrderNo = etOrderMapping.getXhOrderNo(); String xhOrderNo = etOrderMapping.getXhOrderNo();
String pushOrderkey = "pushOrder:".concat(xhOrderNo); String pushOrderkey = "pushOrder:".concat(xhOrderNo);
Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderkey); Map<String, Object> pushOrder = REDIS.getCacheMap(pushOrderkey);
if (pushOrder == null || (pushOrder.get("isStopNotified") != null && (Boolean) pushOrder.get("isStopNotified"))) { if (pushOrder == null || (pushOrder.get("isStopNotified") != null && (Boolean) pushOrder.get("isStopNotified"))) {
return failCommonResponse(queryStopChargeResponse); return failCommonResponse(queryStopChargeResponse, "已下发停止充电指令");
} }
//充电设备接口编码枪编码 //充电设备接口编码枪编码
String connectorId = queryStopChargeRequest.getConnectorId(); String connectorId = queryStopChargeRequest.getConnectorId();
@ -114,15 +114,15 @@ public class QueryStopChargeController {
return commonResponse; return commonResponse;
} }
private CommonResponse failCommonResponse(QueryStopChargeResponse queryStopChargeResponse) throws JsonProcessingException { private CommonResponse failCommonResponse(QueryStopChargeResponse queryStopChargeResponse, String msg) throws JsonProcessingException {
queryStopChargeResponse.setStartChargeSeqStat(5); queryStopChargeResponse.setStartChargeSeqStat(5);
queryStopChargeResponse.setSuccStat(1); queryStopChargeResponse.setSuccStat(1);
queryStopChargeResponse.setFailReason(0); queryStopChargeResponse.setFailReason(0);
String data = JSONUtil.toJSONString(queryStopChargeResponse); String data = JSONUtil.toJSONString(queryStopChargeResponse);
CommonResponse commonResponse = new CommonResponse(); CommonResponse commonResponse = new CommonResponse();
commonResponse.setRet("1"); commonResponse.setRet("0");
commonResponse.setMsg("请求停止充电失败:错误的充电订单号"); commonResponse.setMsg(msg);
commonResponse.setData(data); commonResponse.setData(data);
return commonResponse; return commonResponse;
} }

View File

@ -41,13 +41,16 @@ public class QueryTokenController {
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
resp.setRet("0"); resp.setRet("0");
resp.setMsg(""); resp.setMsg("");
String decodedData = (String) tokenRequest.getAdditionalProperties().get("Data");
try {
tokenRequest = JSONUtil.readParams(decodedData, TokenRequest.class);
} catch (Exception e) {
log.error("invalid Data string: {}", decodedData);
}
String operatorID = tokenRequest.getOperatorId(); String operatorID = tokenRequest.getOperatorId();
if (operatorID == null) {
String decodedData = (String) tokenRequest.getAdditionalProperties().get("Data");
try {
tokenRequest = JSONUtil.readParams(decodedData, TokenRequest.class);
} catch (Exception e) {
log.error("invalid Data string: {}", decodedData);
}
}
operatorID = tokenRequest.getOperatorId();
TokenResponse tokenResponse = new TokenResponse(); TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setOperatorId("MA6DFCTD5"); tokenResponse.setOperatorId("MA6DFCTD5");
tokenResponse.setSuccStat(0); tokenResponse.setSuccStat(0);

View File

@ -76,18 +76,20 @@ public class EvcsFilter extends OncePerRequestFilter {
CommonRequest commonRequest = JSONUtil.readParams(bodyString, CommonRequest.class); CommonRequest commonRequest = JSONUtil.readParams(bodyString, CommonRequest.class);
String operatorId = commonRequest.getOperatorId(); String operatorId = commonRequest.getOperatorId();
String authorization = request.getHeader("Authorization"); String authorization = request.getHeader("Authorization");
log.debug("Authorization: {}", authorization);
AuthSecretToken authSecretTokenIn; AuthSecretToken authSecretTokenIn;
Date now = Calendar.getInstance().getTime(); Date now = Calendar.getInstance().getTime();
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response); ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
if (servletPath.endsWith("query_token")) { if (servletPath.endsWith("query_token")) {
if (!handleQueryToken(request, response, chain, requestWrapper, bodyString, commonRequest, operatorId, if (!handleQueryToken(request, response, chain, requestWrapper, bodyString, commonRequest, operatorId,
responseWrapper)) return; responseWrapper)) return;
} else if (authorization != null && authorization.startsWith("Bearer ")) { }
String token = authorization.substring(7); if (authorization != null && authorization.startsWith("Bearer ")) {
String token = authorization.replace("Bearer ", "");
authSecretTokenIn = authSecretTokenIn =
authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndTokenExpiryGreaterThan( authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenTypeAndTokenExpiryGreaterThan(
operatorId, AuthSecretToken.SECRET_TOKEN_TYPE_IN, now).orElse(null); operatorId, AuthSecretToken.SECRET_TOKEN_TYPE_IN, now).orElse(null);
if (authSecretTokenIn == null || !token.equals(authSecretTokenIn.getToken())) { if (authSecretTokenIn == null) {
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
resp.setRet("4003"); resp.setRet("4003");
resp.setMsg("Invalid token"); resp.setMsg("Invalid token");
@ -96,34 +98,36 @@ public class EvcsFilter extends OncePerRequestFilter {
responseWrapper = new ContentCachingResponseWrapper(response); responseWrapper = new ContentCachingResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper); chain.doFilter(requestWrapper, responseWrapper);
return; return;
} else if (!token.equals(authSecretTokenIn.getToken())) {
log.error("op[{}] Invalid auth: {}", operatorId, authorization);
} }
} else {
log.error("op[{}] Invalid auth: {}", operatorId, authorization);
CommonResponse resp = new CommonResponse();
resp.setRet("4003");
resp.setMsg("Authorization header is not present or invalid");
String data = JSONUtil.toJSONString(resp);
response.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
responseWrapper = new ContentCachingResponseWrapper(response);
chain.doFilter(requestWrapper, responseWrapper);
return;
} }
//decrypt request //decrypt request
byte[] decryptedReq = null; byte[] decryptedReq = null;
String erroMsg = "Decryption error"; String erroMsg = "Decryption error";
CommonResponse resp = new CommonResponse(); CommonResponse resp = new CommonResponse();
authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId, try {
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
if (authSecretTokenIn != null) {
if (servletPath.endsWith("query_token") ||
(now.before(authSecretTokenIn.getTokenExpiry())
&& authorization != null && authorization.substring(7).equals(authSecretTokenIn.getToken()))) {
try {
// if (authSecretTokenIn.isEncrypt() && !"false".equals(encin)) { // test code // if (authSecretTokenIn.isEncrypt() && !"false".equals(encin)) { // test code
decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString); decryptedReq = decrypt(request, authSecretTokenIn, commonRequest, bodyString);
// } else { // } else {
// String data = commonRequest.getData(); // String data = commonRequest.getData();
// if (data == null) data = bodyString; // if (data == null) data = bodyString;
// decryptedReq = data.getBytes(StandardCharsets.UTF_8); // decryptedReq = data.getBytes(StandardCharsets.UTF_8);
// } // }
commonRequest.setData(new String(decryptedReq)); commonRequest.setData(new String(decryptedReq));
log.debug("in.dec: {}", commonRequest); log.debug("in.dec: {}", commonRequest);
} catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) { } catch (BadPaddingException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException e) {
erroMsg = e.getMessage(); erroMsg = e.getMessage();
}
} else {
erroMsg = "Authorization error, check OperatorID or token expiry";
}
} }
if (decryptedReq != null && decryptedReq.length > 0) { if (decryptedReq != null && decryptedReq.length > 0) {
requestWrapper = new HttpServletRequestWritableWrapper(request, requestWrapper = new HttpServletRequestWritableWrapper(request,
@ -170,11 +174,10 @@ public class EvcsFilter extends OncePerRequestFilter {
} }
} }
private boolean handleQueryToken(HttpServletRequest request, private boolean handleQueryToken(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
HttpServletResponse response, FilterChain chain,
ServletRequest requestWrapper, String bodyString, CommonRequest commonRequest, ServletRequest requestWrapper, String bodyString, CommonRequest commonRequest,
String operatorId, String operatorId, ContentCachingResponseWrapper responseWrapper) throws IOException,
ContentCachingResponseWrapper responseWrapper) throws IOException, ServletException { ServletException {
AuthSecretToken authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId, AuthSecretToken authSecretTokenIn = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId,
AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null); AuthSecretToken.SECRET_TOKEN_TYPE_IN).orElse(null);
@ -279,50 +282,42 @@ public class EvcsFilter extends OncePerRequestFilter {
byte[] buf = new byte[]{}; byte[] buf = new byte[]{};
final String encin = request.getHeader("enc.in"); final String encin = request.getHeader("enc.in");
if ("POST".equalsIgnoreCase(request.getMethod())) { if (request.getServletPath().endsWith("/query_token")) {
if (request.getServletPath().endsWith("/query_token")) { String data;
String data; if (("false".equals(encin)) || commonRequest.getData() == null) {
if ((encin != null && "false".equals(encin)) || commonRequest.getData() == null) { data = bodyString;
data = bodyString;
} else if (commonRequest.getData() == null) {
data = Aes128Cbc.decryptString(bodyString, authSecretToken.getDataSecret(), authSecretToken
.getDataSecretIV());
} else {
data = Aes128Cbc.decryptString(commonRequest.getData(), authSecretToken.getDataSecret(), authSecretToken
.getDataSecretIV());
}
buf = data.getBytes(StandardCharsets.UTF_8);
} else { } else {
String authorization = request.getHeader("Authorization"); data = Aes128Cbc.decryptString(commonRequest.getData(), authSecretToken.getDataSecret(), authSecretToken
if (authorization != null && authorization.startsWith("Bearer ")) { .getDataSecretIV());
//decrypt Data field }
buf = bodyString.getBytes(StandardCharsets.UTF_8); buf = data.getBytes(StandardCharsets.UTF_8);
ObjectMapper objectMapper = new ObjectMapper(); } else {
JsonNode rootNode = objectMapper.readTree(buf); //decrypt Data field
JsonNode sigNode = rootNode.path("Sig"); buf = bodyString.getBytes(StandardCharsets.UTF_8);
JsonNode operatorIDNode = rootNode.path("OperatorID"); ObjectMapper objectMapper = new ObjectMapper();
JsonNode dataNode = rootNode.path("Data"); JsonNode rootNode = objectMapper.readTree(buf);
JsonNode timestampNode = rootNode.path("TimeStamp"); JsonNode sigNode = rootNode.path("Sig");
JsonNode seqNode = rootNode.path("Seq"); JsonNode operatorIDNode = rootNode.path("OperatorID");
if (!dataNode.isNull()) { JsonNode dataNode = rootNode.path("Data");
if (!dataNode.asText().startsWith("{")) { JsonNode timestampNode = rootNode.path("TimeStamp");
String computedSig = HMAC.hmacDigest( JsonNode seqNode = rootNode.path("Seq");
operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()), if (!dataNode.isNull()) {
authSecretToken.getSigSecret()); if (!dataNode.asText().startsWith("{")) {
if ((encin == null || !"false".equals(encin)) && !computedSig.equals(sigNode.asText())) { String computedSig = HMAC.hmacDigest(
throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig)); operatorIDNode.asText().concat(dataNode.asText()).concat(timestampNode.asText()).concat(seqNode.asText()),
} authSecretToken.getSigSecret());
} if (("false".equals(encin)) && !computedSig.equals(sigNode.asText())) {
String rawData = dataNode.asText(); throw new InvalidAlgorithmParameterException("Illegal Sig, computed: ".concat(computedSig));
String decryptedData = rawData;
if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) {
decryptedData = Aes128Cbc.decryptString(rawData, authSecretToken.getDataSecret(),
authSecretToken.getDataSecretIV());
((ObjectNode) rootNode).put("Data", decryptedData);
}
buf = decryptedData.getBytes();//rootNode.toString().getBytes();
} }
} }
String rawData = dataNode.asText();
String decryptedData = rawData;
if ((encin == null || encin.equals("true")) || authSecretToken.isEncrypt()) {
decryptedData = Aes128Cbc.decryptString(rawData, authSecretToken.getDataSecret(),
authSecretToken.getDataSecretIV());
((ObjectNode) rootNode).put("Data", decryptedData);
}
buf = decryptedData.getBytes();//rootNode.toString().getBytes();
} }
} }
return buf; return buf;

View File

@ -76,7 +76,6 @@ public class NotificationCancelOrderTask extends CoreDispatcher {
public void notify(CancelOrderRequest cancelOrderRequest, AuthSecretToken authSecretTokenOut, String orderNo) throws JsonProcessingException { public void notify(CancelOrderRequest cancelOrderRequest, AuthSecretToken authSecretTokenOut, String orderNo) throws JsonProcessingException {
String data = JSONUtil.toJSONString(cancelOrderRequest); String data = JSONUtil.toJSONString(cancelOrderRequest);
//logger.debug(data);
CommonRequest<CancelOrderRequest> commonRequest = new CommonRequest<>(); CommonRequest<CancelOrderRequest> commonRequest = new CommonRequest<>();
commonRequest.setData(data); commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_cancel_order", authSecretTokenOut); String responseBody = ok(commonRequest, "/notification_cancel_order", authSecretTokenOut);

View File

@ -76,7 +76,6 @@ public class NotificationChargeOrderInfo4BonusTask extends CoreDispatcher {
etOrderMapping); etOrderMapping);
operatorIdEvcs = operatorIdEvcs == null ? "MA6DFCTD5" : operatorIdEvcs; operatorIdEvcs = operatorIdEvcs == null ? "MA6DFCTD5" : operatorIdEvcs;
String data = JSONUtil.toJSONString(cdChargeOrderInfo4BonusReq); String data = JSONUtil.toJSONString(cdChargeOrderInfo4BonusReq);
logger.debug(data);
CommonRequest<CDChargeOrderInfo4BonusReq> commonRequest = new CommonRequest<>(); CommonRequest<CDChargeOrderInfo4BonusReq> commonRequest = new CommonRequest<>();
commonRequest.setData(data); commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_charge_order_info_for_bonus", authSecretTokenOut); String responseBody = ok(commonRequest, "/notification_charge_order_info_for_bonus", authSecretTokenOut);

View File

@ -69,7 +69,6 @@ public class NotificationStartChargeResultTask extends CoreDispatcher {
String operatorIdEvcs = "MA6DFCTD5"; String operatorIdEvcs = "MA6DFCTD5";
String data = JSONUtil.toJSONString(notificationStartChargeResultRequestData); String data = JSONUtil.toJSONString(notificationStartChargeResultRequestData);
logger.debug(data);
CommonRequest<NotificationStartChargeResultRequestData> commonRequest = new CommonRequest<>(); CommonRequest<NotificationStartChargeResultRequestData> commonRequest = new CommonRequest<>();
commonRequest.setData(data); commonRequest.setData(data);
String responseBody = ok(commonRequest, "/notification_start_charge_result", authSecretTokenOut); String responseBody = ok(commonRequest, "/notification_start_charge_result", authSecretTokenOut);