Java接口安全
拦截器
package com.javasm.shirospringboot.interceptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ApiInterceptor extends HandlerInterceptorAdapter {
private static Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);
private static final long REQUEST_TIMEOUT_EXPIRE = 10 * 60 * 1000;
private static final String UTF8 = "utf-8";
private static final String CONTENT_TYPE = "application/json";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
String sign = request.getParameter("sign");
if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
AuthCheck authCheck = ((HandlerMethod) handler).getMethodAnnotation(AuthCheck.class);
if(authCheck == null || authCheck.validate() == false){
return true;
}else{
String timestamp = request.getParameter("timestamp");
if (StringUtils.isBlank(timestamp)) {
logger.error("签名参数timestamp'{}'为空 requestInfo:{}", timestamp, request.getServletPath());
responseJson(response, "{\"flag\":false,\""+Constants.STATUS+"\":"+CodeConstants.CONNCODECHECK+",\"msg\":\"非法请求,服务器已拒绝!\"}");
return false;
}
long clientTimestamp = new Long(timestamp);
if (!(Math.abs(System.currentTimeMillis() - clientTimestamp) < REQUEST_TIMEOUT_EXPIRE)) {
logger.error("请求已过期 clientTimestampStr:{} requestInfo:{}", timestamp, request.getServletPath());
responseJson(response, "{\"flag\":false,\""+Constants.STATUS+"\":"+CodeConstants.CONNCODECHECK+",\"msg\":\"非法请求,服务器已拒绝!\"}");
return false;
}
String serverSign;
Map<String, Object> paramMap = new HashMap<String, Object>();
Map<String, String[]> parameterMap = request.getParameterMap();
for (String key : parameterMap.keySet()) {
paramMap.put(key, getParamValue(parameterMap.get(key)));
}
serverSign = SignUtil.getSign(paramMap);
if (StringUtils.isBlank(serverSign) || !serverSign.equals(sign)) {
logger.error("签名不一致 serverSign:{} clientSign:{} requestInfo:{}", new Object[] { serverSign, sign, request.getServletPath() });
responseJson(response, "{\"flag\":false,\""+Constants.STATUS+"\":"+CodeConstants.CONNCODECHECK+",\"msg\":\"非法请求,服务器已拒绝!\"}");
return false;
}else{
return true;
}
}
}
else
return true;
}
private String getParamValue(String[] paramValues) {
if (paramValues == null) {
return StringUtils.EMPTY;
}
String paramValue = null;
if (paramValues.length == 1) {
paramValue = paramValues[0];
} else if (paramValues.length > 1) {
paramValue = StringUtils.join(paramValues, ",");
}
return StringUtils.defaultString(paramValue);
}
public static void responseJson(HttpServletResponse response, String responseContent) throws IOException {
if (response.isCommitted()) {
logger.info("response.isCommitted()! responseContent:{"+responseContent+"}");
return;
}
response.setCharacterEncoding(UTF8);
response.setContentType(CONTENT_TYPE);
PrintWriter printWriter = response.getWriter();
printWriter.print(responseContent);
printWriter.flush();
printWriter.close();
}
}
自定义权限注解
package com.javasm.shirospringboot.interceptor;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheck {
boolean validate() default true;
}
加密辅助类
package com.javasm.shirospringboot.interceptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
public class SignUtil {
private static String key = "IXCfWBE5dRfyuIcFmhe2ANQ6VmoRZxRP";
public static String getSign(Map<String,Object> map) throws Exception{
ArrayList<String> list = new ArrayList<String>();
for(Map.Entry<String,Object> entry:map.entrySet()){
if(!entry.getValue().equals("")&& !entry.getKey().equals("sign")){
list.add(entry.getKey() + "=" + entry.getValue() + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
result = MD5Encrypt.encrypt(result).toUpperCase();
return result;
}
}