一、业务背景
调用第三方接口或者前后端分离开发,调用业务接口时为防止刷机/违规调用等现象 需要加验签机制,比如支付类等接口,接口双方为了确保数据参数在传输过程中未经过篡改,都需要对接口数据进行加签,然后在接口服务器端对接口参数进行验签,确保两个签名是一样的,验签通过之后再进行业务逻辑处理。
二、处理思路
签名验签的大方向无非就是:客户端与服务端约定好,按照统一算法,统一参数,统一顺序,统一密钥 进行加密,然后作对比;我这里就介绍一种比较简单实用且常用的签名/验签方式思路:
客户端:
签名通过header传到服务端,key名为:token
签名:API版本号+AK+签名过期时间+密钥(SK)+URL+requestMethod+客户端已排序的参数 做加密;
加密算法:MD5;
密钥(SK): 前后端统一,签名加密的时候使用相当于加盐;
AK : 多客户端使用不同的SK, 服务端就需要通过AK找到对应的SK进行加密验签;
签名过期时间:客户端定义的签名过期时间,超过该时间该签名请求不可通过;
请求参数:已排序的参数通过request-line 或 request-body传到服务端
服务端:
同样的方式进行签名,验证。以确认调用者是否合法,这就是接口签名验证的思路。
服务器端代码如下(仅供参考):
通过spring拦截器HandlerInterceptor(其内部将request请求body参数转为line参数,So,直接getParameter)
/**
* @Description:验签拦截
* @Author pengju
* @date 2018/4/11 13:44
*/
public class ApiAkSkInterceptor implements HandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(ApiAkSkInterceptor.class);
@Autowired
private BaseOpenApiConfig baseOpenApiConfig;
/**
* Intercept the execution of a handler. Called after HandlerMapping determined
* an appropriate handler object, but before HandlerAdapter invokes the handler.
* <p>DispatcherServlet processes a handler in an execution chain, consisting
* of any number of interceptors, with the handler itself at the end.
* With this method, each interceptor can decide to abort the execution chain,
* typically sending a HTTP error or writing a custom response.
* <p><strong>Note:</strong> special considerations apply for asynchronous
* request processing. For more details see
* {@link AsyncHandlerInterceptor}.
*
* @param request current HTTP request
* @param response current HTTP response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return {@code true} if the execution chain should proceed with the
* next interceptor or the handler itself. Else, DispatcherServlet assumes
* that this interceptor has already dealt with the response itself.
* @throws Exception in case of errors
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler == null || !(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handlerMethod.getBeanType().isAnnotationPresent(ApiAkSkNotValidator.class)
|| handlerMethod.getMethod().isAnnotationPresent(ApiAkSkNotValidator.class)) {
return true;
}
final long bt = System.currentTimeMillis();
response.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
try {
// get header token
String requestUri = request.getRequestURI();
final String requestMethod = request.getMethod();
final String token = request.getHeader(TokenHelper.X_IBEE_AUTH_TOKEN);
logger.info("checkApiAkSkToken: check token,request uri={},method={},header token={}", requestUri, requestMethod, token);
// token
if (StringUtils.isBlank(token) || token.split("-").le