feat: HCS认证改为固定Authorization+Key-Auth静态双请求头(v4接口说明变更)

- 所有接口由拦截器统一注入 Authorization(整值可配)+ Key-Auth,不再调用getToken取令牌
- 删除 oauth2/getToken 与 basic 双模式、HcsTokenService/HcsTokenVO 及 Redis 令牌缓存、blade-starter-redis 依赖
- 新配置项 third-party.hcs.authorization / key-auth,未配置时告警放行(对端401暴露配置缺失)
- 各接口路径维持 thirdParty.hcs.*Url 覆盖机制,网关前缀拼在 base-url(如 /gwzh/HTHG)
This commit is contained in:
刘泉佳
2026-10-01 02:06:34 +08:00
parent 1906e8c80b
commit 6255d65e21
8 changed files with 36 additions and 324 deletions
@@ -15,10 +15,6 @@
<description>BladeX 合同合规系统(HCS)API 契约模块</description>
<dependencies>
<dependency>
<groupId>org.springblade</groupId>
<artifactId>blade-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@@ -28,8 +28,6 @@ package org.springblade.hcs.config;
import feign.Request;
import feign.RequestInterceptor;
import org.springblade.hcs.interceptor.HcsAuthInterceptor;
import org.springblade.hcs.token.HcsTokenService;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Bean;
import java.util.concurrent.TimeUnit;
@@ -52,12 +50,11 @@ public class HcsFeignClientConfig {
}
/**
* HCS 认证拦截器。以 ObjectProvider 惰性持有令牌服务,
* 避免 Feign 客户端构建(需拦截器)与令牌服务(依赖 Feign 客户端取令牌)之间的构造期循环依赖
* HCS 认证拦截器:所有请求注入 Authorization + Key-Auth 两个静态认证头(v4 接口说明)
*/
@Bean
public RequestInterceptor hcsAuthInterceptor(HcsProperties properties, ObjectProvider<HcsTokenService> tokenServiceProvider) {
return new HcsAuthInterceptor(properties, tokenServiceProvider);
public RequestInterceptor hcsAuthInterceptor(HcsProperties properties) {
return new HcsAuthInterceptor(properties);
}
@Bean
@@ -26,7 +26,6 @@
package org.springblade.hcs.config;
import lombok.Data;
import org.springblade.hcs.constant.HcsConstant;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.HashMap;
@@ -45,29 +44,18 @@ import java.util.Map;
@ConfigurationProperties(prefix = "third-party.hcs")
public class HcsProperties {
/**
* 合同合规系统(HCS)接口基础地址,直连可配(网关/iPaaS 部署时改此处,代码不感知)
* 合同合规系统(HCS)接口基础地址,直连可配(网关/iPaaS 部署时改此处,代码不感知)。
* v4 接口说明:地址带网关前缀,如 http://172.16.203.134:8000/gwzh/HTHG
*/
private String baseUrl;
/**
* 认证方式:oauth2(默认,URL 追加 access_token)| basic(Authorization 请求头),切换不改代码
* Authorization 请求头整值(含 Basic 前缀,如 Basic d2Njazp...,凭据走 Nacos + 环境变量注入)
*/
private String authType = HcsConstant.AUTH_TYPE_OAUTH2;
private String authorization;
/**
* OAuth2 应用 appKey
* Key-Auth 请求头值(v4 接口说明:所有接口固定携带 Authorization + Key-Auth 两个头)
*/
private String appKey;
/**
* OAuth2 应用 appSecret
*/
private String appSecret;
/**
* Basic 认证用户名
*/
private String basicUsername;
/**
* Basic 认证密码
*/
private String basicPassword;
private String keyAuth;
/**
* 来源系统标识(fd_sources,D14 约定值 TMS)
*/
@@ -38,42 +38,12 @@ public class HcsConstant {
public static final String SUCCESS_CODE = "return.optSuccess";
/**
* 认证方式:OAuth2(默认,URL 追加 access_token)
*/
public static final String AUTH_TYPE_OAUTH2 = "oauth2";
/**
* 认证方式:Basic(Authorization 请求头)
*/
public static final String AUTH_TYPE_BASIC = "basic";
/**
* 网关认证请求头名称
* 网关认证请求头名称(整值可配,如 Basic d2Njazp...)
*/
public static final String HEADER_AUTHORIZATION = "Authorization";
/**
* Basic 认证请求头前缀
* 网关 Key-Auth 认证请求头名称(v4 接口说明:所有接口固定携带)
*/
public static final String HEADER_BASIC_PREFIX = "Basic ";
/**
* OAuth2 access_token 追加到业务请求 URL 的参数名
*/
public static final String QUERY_ACCESS_TOKEN = "access_token";
/**
* HCS access_token 缓存 key(照 BFI 令牌缓存命名惯例)
*/
public static final String HCS_TOKEN_CACHE_KEY = "blade:third:hcs:token";
/**
* token 提前失效缓冲时长(毫秒),防止刚好过期(照 BFI 120s 缓冲)
*/
public static final long TOKEN_EXPIRE_BUFFER_MILLIS = 120_000L;
/**
* getToken 接口默认路径片段,拦截器据此跳过令牌追加(避免给取令牌请求再带 access_token)
*/
public static final String GET_TOKEN_PATH = "/authapi/getToken";
public static final String HEADER_KEY_AUTH = "Key-Auth";
}
@@ -1,63 +0,0 @@
/**
* BladeX Commercial License Agreement
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
* <p>
* Use of this software is governed by the Commercial License Agreement
* obtained after purchasing a license from BladeX.
* <p>
* 1. This software is for development use only under a valid license
* from BladeX.
* <p>
* 2. Redistribution of this software's source code to any third party
* without a commercial license is strictly prohibited.
* <p>
* 3. Licensees may copyright their own code but cannot use segments
* from this software for such purposes. Copyright of this software
* remains with BladeX.
* <p>
* Using this software signifies agreement to this License, and the software
* must not be used for illegal purposes.
* <p>
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
* not liable for any claims arising from secondary or illegal development.
* <p>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.hcs.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
* 合同合规系统(HCS)OAuth2 取令牌返回结果(GET /authapi/getToken)
* <p>
* TODO 待联调确认:v4 文档未给出本接口响应字段示例,字段名按通用 OAuth2 惯例预置,
* 联调时以实际返回为准(设计文档 §3.2)。
*
* @author Chill
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class HcsTokenVO implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 访问令牌,调用业务接口时追加到 URL 参数 access_token
*/
@JsonProperty("access_token")
private String accessToken;
/**
* 令牌类型
*/
@JsonProperty("token_type")
private String tokenType;
/**
* 令牌有效期(毫秒)
*/
@JsonProperty("expires_in")
private Long expiresIn;
}
@@ -56,10 +56,8 @@ import org.springblade.hcs.dto.HcsRiskQueryDTO;
import org.springblade.hcs.dto.HcsRiskVO;
import org.springblade.hcs.dto.HcsSpecPaySaveDTO;
import org.springblade.hcs.dto.HcsTemplateVO;
import org.springblade.hcs.dto.HcsTokenVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
@@ -67,7 +65,11 @@ import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
/**
* 合同合规系统(HCS)接口(一期 24 个业务接口 + OAuth2 取令牌,D4)
* 合同合规系统(HCS)接口(一期 24 个业务接口,D4)
* <p>
* v4 接口说明:认证统一由 {@link org.springblade.hcs.interceptor.HcsAuthInterceptor} 注入
* Authorization + Key-Auth 两个静态请求头,不再调用 getToken 取令牌;
* 各接口路径可用 thirdParty.hcs.*Url 配置覆盖(默认值即 v4 文档路径)。
* <p>
* 除附件上传(multipart/form-data)、附件下载(文件流)外均为 POST + application/json(UTF-8)。
* 业务成败以统一出参 {@link HcsResult#isSuccess()} 为准;
@@ -78,7 +80,6 @@ import org.springframework.web.multipart.MultipartFile;
@FeignClient(name = "HCS", url = "${thirdParty.hcs.baseUrl}", configuration = HcsFeignClientConfig.class)
public interface IHcsClient {
String GET_TOKEN_URL = "${thirdParty.hcs.getTokenUrl:/authapi/getToken}";
String PROJECT_ADD_URL = "${thirdParty.hcs.projectAddUrl:/openapi/sys-modeling/apis/data/km-project1/V1/projectApproval/add}";
String PROJECT_UPDATE_URL = "${thirdParty.hcs.projectUpdateUrl:/openapi/sys-modeling/apis/data/km-project1/V1/projectApproval/update}";
String PROJECT_LIST_URL = "${thirdParty.hcs.projectListUrl:/openapi/sys-modeling/apis/data/km-project1/V1/projectApproval/list}";
@@ -104,16 +105,6 @@ public interface IHcsClient {
String INVOICE_REG_ADD_URL = "${thirdParty.hcs.invoiceRegAddUrl:/openapi/eop-data/eopDataInvoiceRegistrationOpen/add}";
String INVOICE_REG_UPDATE_URL = "${thirdParty.hcs.invoiceRegUpdateUrl:/openapi/eop-data/eopDataInvoiceRegistrationOpen/update}";
/**
* OAuth2 获取令牌(appKey/appSecret 走 URL 参数,D2)
*
* @param appKey 应用 appKey
* @param appSecret 应用 appSecret
* @return 令牌信息
*/
@GetMapping(GET_TOKEN_URL)
HcsResult<HcsTokenVO> getToken(@RequestParam("appKey") String appKey, @RequestParam("appSecret") String appSecret);
/**
* C102-1 项目立项新建
*
@@ -29,22 +29,18 @@ import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.hcs.config.HcsProperties;
import org.springblade.hcs.constant.HcsConstant;
import org.springblade.hcs.token.HcsTokenService;
import org.springframework.beans.factory.ObjectProvider;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* 合同合规系统(HCS)请求拦截器,按配置的认证方式注入凭据(D2,两种实现并存、切换不改代码)
* 合同合规系统(HCS)请求拦截器(v4 接口说明,D2)
* <p>
* 所有业务接口统一注入两个静态认证头,不再走 getToken/令牌缓存:
* <ul>
* <li>oauth2(默认):GET /authapi/getToken 取令牌后,把 access_token 追加到业务请求 URL;</li>
* <li>basic:注入 Authorization: Basic base64(user:password) 请求头。</li>
* <li>Authorization:整值可配(如 Basic d2Njazp...,含前缀);</li>
* <li>Key-Auth:网关密钥,整值可配。</li>
* </ul>
* 取令牌请求本身不追加 access_token(路径守卫 + 空令牌守卫双重防护)。
* 两个头均来自 Nacos + 环境变量注入,未配置时告警并放行(由对端返回 401 暴露问题)。
*
* @author Chill
*/
@@ -54,46 +50,23 @@ public class HcsAuthInterceptor implements RequestInterceptor {
private final HcsProperties properties;
/**
* 惰性持有令牌服务,打破 Feign 客户端与令牌服务的构造期循环依赖
*/
private final ObjectProvider<HcsTokenService> tokenServiceProvider;
@Override
public void apply(RequestTemplate template) {
if (HcsConstant.AUTH_TYPE_BASIC.equals(properties.getAuthType())) {
applyBasicAuth(template);
return;
String authorization = properties.getAuthorization();
if (isBlank(authorization)) {
log.warn("HCS Authorization 请求头未配置(thirdParty.hcs.authorization),请求 {} 将无认证头", template.path());
} else {
template.header(HcsConstant.HEADER_AUTHORIZATION, authorization);
}
String keyAuth = properties.getKeyAuth();
if (isBlank(keyAuth)) {
log.warn("HCS Key-Auth 请求头未配置(thirdParty.hcs.key-auth),请求 {} 将无认证头", template.path());
} else {
template.header(HcsConstant.HEADER_KEY_AUTH, keyAuth);
}
applyOAuth2Token(template);
}
/**
* Basic 认证:注入 Authorization 请求头(凭据走 Nacos + 环境变量注入)
*/
private void applyBasicAuth(RequestTemplate template) {
if (StringUtil.isBlank(properties.getBasicUsername()) || StringUtil.isBlank(properties.getBasicPassword())) {
log.warn("HCS Basic 认证凭据未配置(thirdParty.hcs.basic-username/basic-password),请求 {} 将无认证头", template.path());
return;
}
String credentials = properties.getBasicUsername() + ":" + properties.getBasicPassword();
String encoded = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
template.header(HcsConstant.HEADER_AUTHORIZATION, HcsConstant.HEADER_BASIC_PREFIX + encoded);
}
/**
* OAuth2 认证:业务请求 URL 追加 access_token 参数
*/
private void applyOAuth2Token(RequestTemplate template) {
// 取令牌请求本身不再追加 access_token
if (template.path() != null && template.path().contains(HcsConstant.GET_TOKEN_PATH)) {
return;
}
String accessToken = tokenServiceProvider.getObject().getAccessToken();
if (StringUtil.isBlank(accessToken)) {
log.warn("HCS access_token 为空,请求 {} 未追加令牌参数", template.path());
return;
}
template.query(HcsConstant.QUERY_ACCESS_TOKEN, accessToken);
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
@@ -1,140 +0,0 @@
/**
* BladeX Commercial License Agreement
* Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
* <p>
* Use of this software is governed by the Commercial License Agreement
* obtained after purchasing a license from BladeX.
* <p>
* 1. This software is for development use only under a valid license
* from BladeX.
* <p>
* 2. Redistribution of this software's source code to any third party
* without a commercial license is strictly prohibited.
* <p>
* 3. Licensees may copyright their own code but cannot use segments
* from this software for such purposes. Copyright of this software
* remains with BladeX.
* <p>
* Using this software signifies agreement to this License, and the software
* must not be used for illegal purposes.
* <p>
* THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
* not liable for any claims arising from secondary or illegal development.
* <p>
* Author: Chill Zhuang (bladejava@qq.com)
*/
package org.springblade.hcs.token;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.hcs.config.HcsProperties;
import org.springblade.hcs.constant.HcsConstant;
import org.springblade.hcs.dto.HcsResult;
import org.springblade.hcs.dto.HcsTokenVO;
import org.springblade.hcs.exception.HcsException;
import org.springblade.hcs.feign.IHcsClient;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.Objects;
/**
* 合同合规系统(HCS)OAuth2 令牌服务(D2,照 BfiServiceImpl 惯例)
* <p>
* GET /authapi/getToken(appKey/appSecret)→ access_token 存 Redis
* (key {@link HcsConstant#HCS_TOKEN_CACHE_KEY},过期前留 120s 缓冲)。
* 业务调用统一经 {@link #getAccessToken()} 取缓存令牌;
* 401 时调用 {@link #refreshAccessToken()} 强制刷新一次后重放(D7,重试职责归扫描任务,此处仅刷新令牌)。
* auth-type=basic 时不走本服务,由拦截器注入 Basic 认证头。
*
* @author Chill
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class HcsTokenService {
private final HcsProperties properties;
private final IHcsClient client;
private final BladeRedis bladeRedis;
/**
* 获取访问令牌:Redis 命中直接返回,未命中远端取令牌并缓存
*
* @return access_token
*/
public String getAccessToken() {
String token = bladeRedis.get(HcsConstant.HCS_TOKEN_CACHE_KEY);
if (StringUtil.isNotBlank(token)) {
return token;
}
return requestToken();
}
/**
* 强制刷新访问令牌(401 时调用一次并重放请求)
*
* @return 新 access_token
*/
public String refreshAccessToken() {
log.info("强制刷新HCS令牌,清除本地缓存");
bladeRedis.del(HcsConstant.HCS_TOKEN_CACHE_KEY);
return requestToken();
}
/**
* 远端取令牌并缓存
*
* @return access_token
*/
private String requestToken() {
if (StringUtil.isBlank(properties.getAppKey()) || StringUtil.isBlank(properties.getAppSecret())) {
throw new HcsException("获取HCS令牌失败,appKey/appSecret 未配置(thirdParty.hcs.app-key/app-secret)");
}
long start = System.currentTimeMillis();
log.info("调用HCS接口 获取令牌开始");
HcsResult<HcsTokenVO> result = client.getToken(properties.getAppKey(), properties.getAppSecret());
log.info("调用HCS接口 获取令牌结束 耗时:{}ms,success:{}", System.currentTimeMillis() - start, result.isSuccess());
if (result == null || !result.isSuccess()) {
log.error("调用HCS接口 获取令牌失败响应:{}", result == null ? "无响应" : String.format("code=%s, msg=%s, traceId=%s",
result.getCode(), result.getMsg(), result.getTraceId()));
throw new HcsException("调用HCS接口获取令牌异常 " + (result == null ? "响应为空" : result.getMsg()));
}
HcsTokenVO tokenVO = result.getData();
if (tokenVO == null || StringUtil.isBlank(tokenVO.getAccessToken())) {
log.error("调用HCS接口 获取令牌返回数据为空");
throw new HcsException("调用HCS接口获取令牌异常,返回数据为空");
}
cacheToken(tokenVO);
return tokenVO.getAccessToken();
}
/**
* 缓存令牌,按 expires_in 毫秒数设置提前失效时间
* <p>
* TODO 待联调确认:v4 未给出 getToken 响应字段示例,expires_in 字段名与单位以实际返回为准(设计文档 §3.2)
*
* @param tokenVO 令牌信息
*/
private void cacheToken(HcsTokenVO tokenVO) {
if (tokenVO.getExpiresIn() == null || tokenVO.getExpiresIn() <= HcsConstant.TOKEN_EXPIRE_BUFFER_MILLIS) {
log.warn("HCS令牌未返回有效期或有效期不足缓冲时长,本次不缓存");
return;
}
// 过期时间 - 缓冲时长,防止刚好过期
long expireMillis = tokenVO.getExpiresIn() - HcsConstant.TOKEN_EXPIRE_BUFFER_MILLIS;
bladeRedis.getValueOps().setIfAbsent(HcsConstant.HCS_TOKEN_CACHE_KEY, tokenVO.getAccessToken(), Duration.ofMillis(expireMillis));
log.info("HCS令牌已缓存,有效期 {}ms(含 {}ms 提前失效缓冲)", expireMillis, HcsConstant.TOKEN_EXPIRE_BUFFER_MILLIS);
}
/**
* 令牌缓存是否命中(诊断用)
*
* @return true-缓存存在
*/
public boolean isTokenCached() {
return StringUtil.isNotBlank(Objects.toString(bladeRedis.get(HcsConstant.HCS_TOKEN_CACHE_KEY), null));
}
}