springboot?aop配合反射統(tǒng)一簽名驗(yàn)證實(shí)踐
aop配合反射統(tǒng)一簽名驗(yàn)證
直接上代碼,作為記錄。
CheckSignAspect.java
@Aspect //定義一個(gè)切面
@Configuration
@Log4j2
public class CheckSignAspect {
// 定義切點(diǎn)Pointcut
@Pointcut("execution(* com.lsj.xxl.controller.*.*CheckSign(..))")
public void excudeService() {
}
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
String class_name = pjp.getTarget().getClass().getName();
String method_name = pjp.getSignature().getName();
String[] paramNames = getFieldsName(class_name, method_name);
Object[] method_args = pjp.getArgs();
SortedMap<String, String> map = logParam(paramNames, method_args);
if (map != null) {
String sign = map.get("sign").toUpperCase();
map.remove("sign");
String realSign = SignUtil.createSign("utf8", map);
if (!realSign.equals(sign)) {
return "簽名校驗(yàn)錯(cuò)誤";
}
}
Object result = pjp.proceed();
return result;
}
/**
* 使用javassist來(lái)獲取方法參數(shù)名稱
*
* @param class_name 類名
* @param method_name 方法名
* @return
* @throws Exception
*/
private String[] getFieldsName(String class_name, String method_name) throws Exception {
Class<?> clazz = Class.forName(class_name);
String clazz_name = clazz.getName();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(clazz);
pool.insertClassPath(classPath);
CtClass ctClass = pool.get(clazz_name);
CtMethod ctMethod = ctClass.getDeclaredMethod(method_name);
MethodInfo methodInfo = ctMethod.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
return null;
}
String[] paramsArgsName = new String[ctMethod.getParameterTypes().length];
int pos = Modifier.isStatic(ctMethod.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramsArgsName.length; i++) {
paramsArgsName[i] = attr.variableName(i + pos);
}
return paramsArgsName;
}
/**
* 打印方法參數(shù)值 基本類型直接打印,非基本類型需要重寫(xiě)toString方法
*
* @param paramsArgsName 方法參數(shù)名數(shù)組
* @param paramsArgsValue 方法參數(shù)值數(shù)組
*/
private SortedMap<String, String> logParam(String[] paramsArgsName, Object[] paramsArgsValue) {
Map<String, String> map = new HashMap();
if (ArrayUtils.isEmpty(paramsArgsName) || ArrayUtils.isEmpty(paramsArgsValue)) {
log.info("該方法沒(méi)有參數(shù)");
return null;
}
// StringBuffer buffer = new StringBuffer();
for (int i = 0; i < paramsArgsName.length; i++) {
//參數(shù)名
String name = paramsArgsName[i];
//參數(shù)值
Object value = paramsArgsValue[i];
// if ("sign".equals(name)){
// continue;
// }
if (isPrimite(value.getClass())) {
map.put(name, String.valueOf(value));
} else {
map.put(name, value.toString());
}
}
return new TreeMap<>(map);
}
/**
* 判斷是否為基本類型:包括String
*
* @param clazz clazz
* @return true:是; false:不是
*/
private boolean isPrimite(Class<?> clazz) {
if (clazz.isPrimitive() || clazz == String.class) {
return true;
} else {
return false;
}
}
}
SignUtil.java
public class SignUtil {
public static String createSign(String characterEncoding, SortedMap<String, String> parameters) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (!Strings.isNullOrEmpty(entry.getValue()) && !"sign".equals(entry.getKey()) && !"key".equals(entry.getKey())) {
sb.append(entry.getKey() + "=" + entry.getValue() + "&");
}
}
String s = sb.toString();
if (s.length() > 0) {
s = s.substring(0, sb.toString().length() - 1);
}
System.out.println("待加密字符串:" + s);
String sign = MD5Util.MD5Encode(s, characterEncoding).toUpperCase();
return sign;
}
}
測(cè)試
@PostMapping("test1")
public String bbCheckSign( @RequestParam("value") String value,
@RequestParam("bb")String bb,
@RequestParam("sign")String sign){
return "ok";
}
補(bǔ)充:
上述方式也可換為注解實(shí)現(xiàn),具體修改代碼如下:
添加注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME )
public @interface CheckSign {
}
改變切點(diǎn)
@Pointcut("@annotation(com.lsj.xxl.annotation.CheckSign)")
接口統(tǒng)一簽名校驗(yàn)
實(shí)現(xiàn)接口請(qǐng)求簽名校驗(yàn),時(shí)間戳判斷,響應(yīng)數(shù)據(jù)返回簽名等內(nèi)容。
這個(gè)簽名校驗(yàn),和返回簽名可以用多種方法實(shí)現(xiàn)。
第一種aop 方式實(shí)現(xiàn)

自定義注解體
/**
* @author xxx
*/
@Retention(value = RetentionPolicy.RUNTIME)
public @interface SignatureValidation {
}
aop實(shí)現(xiàn)
/**
* @author xxx
*/
@Aspect
@Component
public class SignatureValidation {
/**
* 時(shí)間戳請(qǐng)求最小限制(600s)
* 設(shè)置的越小,安全系數(shù)越高,但是要注意一定的容錯(cuò)性
*/
private static final long MAX_REQUEST = 10 * 60 * 1000L;
/**
* 秘鑰
*/
private static final String SECRET= "test";
/**
* 驗(yàn)簽切點(diǎn)(完整的找到設(shè)置的文件地址)
*/
@Pointcut("execution(@com.xx.xxx.xxxxx.aop.SignatureValidation * *(..))")
private void verifyUserKey() {
}
/**
* 獲取請(qǐng)求數(shù)據(jù),并校驗(yàn)簽名數(shù)據(jù)
*/
@Before("verifyUserKey()")
public void doBasicProfiling(JoinPoint point) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
String sign = "" ;
String timestamp = "" ;
String version = "";
SortedMap<String,String> sortedMap = new TreeMap<String,String>();
for ( Object obj :point.getArgs()) {
JSONObject jsonObject =JSONUtil.parseObj(obj);
if( !StrUtil.isEmptyIfStr(jsonObject.get("sign"))){
sign=jsonObject.get("sign").toString();
}
if(!StrUtil.isEmptyIfStr(jsonObject.get("timestamp"))){
timestamp=jsonObject.get("timestamp").toString();
sortedMap.put("timestamp", timestamp);
}
if(!StrUtil.isEmptyIfStr(jsonObject.get("version"))){
version=jsonObject.get("version").toString();
sortedMap.put("version", version);
}
if(!StrUtil.isEmptyIfStr(jsonObject.get("data"))){
String dataStr= jsonObject.get("data").toString();
if(!JSONUtil.isJsonObj(dataStr)) {
if(JSONUtil.isJsonArray(dataStr)){
sortedMap.put("data", JSONUtil.parseArray(dataStr).toString());
}
sortedMap.put("data", dataStr);
}
else
{
JSONObject dataJson= JSONUtil.parseObj(dataStr);
@SuppressWarnings("unchecked")
Set<String> keySet = dataJson.keySet();
String key = "";
Object value = null;
// 遍歷json數(shù)據(jù),添加到SortedMap對(duì)象
for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
key = iterator.next();
value = dataJson.get(key);
String valueStr="";
if(!StrUtil.isEmptyIfStr(value)){
valueStr=value.toString();
}
sortedMap.put(key, valueStr);
}
}
}
}
if (StrUtil.isEmptyIfStr(sign)) {
throw new CustomException(BaseResultInfoEnum.ERROR_MISSING_SIGN_1009.getMsg(),BaseResultInfoEnum.ERROR_MISSING_SIGN_1009.getCode());
}
//新的簽名
String newSign = createSign(sortedMap,SECRET);
if (!newSign.equals(sign.toUpperCase())) {
throw new CustomException(BaseResultInfoEnum.ERROR_SIGN_1010.getMsg(),BaseResultInfoEnum.ERROR_SIGN_1010.getCode());
}
}
/**
*
* @param point
* @param responseObject 返回參數(shù)
*/
@AfterReturning(pointcut="verifyUserKey()",returning="responseObject")
public void afterReturning(JoinPoint point,Object responseObject) {
HttpServletResponse response=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
if(responseObject instanceof ResponseModel){
ResponseModel responseModel= (ResponseModel) responseObject;
responseModel.setTimestamp(System.currentTimeMillis());
responseModel.setVersion(0);
String sign= Md5Utils.createSign(Md5Utils.createParameters(responseModel),SECRET);
responseModel.setSign(sign);
}
}
}
md5簽名
/**
* @author xxx
*/
public class Md5Utils {
/**
* 生成簽名
* @param parameters
* @param key 商戶ID
* @return
*/
public static String createSign(SortedMap<String,String> parameters, String key){
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
Object v = entry.getValue();
if(null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + key);
String sign = SecureUtil.md5(sb.toString()).toUpperCase();
return sign;
}
/**
* 簽名參數(shù)
* @param responseModel 響應(yīng)數(shù)據(jù)簽名返回給調(diào)用者
* @return
*/
public static SortedMap<String,String> createParameters(ResponseModel responseModel){
SortedMap<String,String> sortedMap = new TreeMap<String,String>();
if(responseModel!=null) {
sortedMap.put("timestamp", Convert.toStr(responseModel.getTimestamp()) );
sortedMap.put("version", Convert.toStr(responseModel.getVersion()));
JSONObject json = JSONUtil.parseObj(responseModel, false);
if(responseModel.getData()!=null) {
sortedMap.put("data", json.get("data").toString());
}
}
return sortedMap;
}
}
使用,在控制中的方法上方注解即可

第二種攔截器
這里只做了時(shí)間判斷,簽名校驗(yàn)可以根據(jù)需要修改即可實(shí)現(xiàn)。

過(guò)濾器
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author xx
*/
@WebFilter(urlPatterns = "/*",filterName = "channelFilter")
public class ChannelFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ServletRequest requestWrapper = null;
if(servletRequest instanceof HttpServletRequest) {
requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
}
if(requestWrapper == null) {
filterChain.doFilter(servletRequest, servletResponse);
} else {
filterChain.doFilter(requestWrapper, servletResponse);
}
}
@Override
public void destroy() {
}
}
攔截器配置
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author xxxx
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getHandlerInterceptor());
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Content-Type", "x-requested-with", "X-Custom-Header")
.allowedMethods("PUT", "POST", "GET", "DELETE", "OPTIONS")
.allowedOrigins("*")
.allowCredentials(true);
}
@Bean
public FilterRegistrationBean repeatedlyReadFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
ChannelFilter repeatedlyReadFilter = new ChannelFilter();
registration.setFilter(repeatedlyReadFilter);
registration.addUrlPatterns("/*");
return registration;
}
@Bean
public HandlerInterceptor getHandlerInterceptor() {
return new TimestampInterceptor();
}
}
RequestWrapper 請(qǐng)求流重寫(xiě)處理
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
* @author xxx
*/
public class RequestWrapper extends HttpServletRequestWrapper {
private final String body;
public RequestWrapper(HttpServletRequest request) {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
InputStream inputStream = null;
try {
inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
} finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
攔截器 這里可以實(shí)現(xiàn)請(qǐng)求來(lái)的簽名處理,這里只處理時(shí)間了
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import xxx.xxx.xxx.common.result.BaseResultInfoEnum;
import xxx.xxx.common.core.exception.CustomException;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author xxx
*/
public class TimestampInterceptor implements HandlerInterceptor {
/**
* 時(shí)間戳請(qǐng)求最小限制(600s)
* 設(shè)置的越小,安全系數(shù)越高,但是要注意一定的容錯(cuò)性
*/
private static final long MAX_REQUEST = 10 * 60 * 1000L;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handlerMethod.getBean() instanceof BasicErrorController) {
return true;
}
// if ("GET".equals(request.getMethod())) {
// return true;
// }
ValidateResponse validateResponse = new ValidateResponse(true, null);
RequestWrapper myRequestWrapper = new RequestWrapper((HttpServletRequest) request);
validateResponse= checkTimestamp(myRequestWrapper.getBody());
if (!validateResponse.isValidate()) {
throw validateResponse.getException();
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
}
private ValidateResponse checkTimestamp(String requestBody) {
try {
JSONObject jsonObject = JSONUtil.parseObj(requestBody);
String timestamp = "" ;
if(!StrUtil.isEmptyIfStr(jsonObject.get("timestamp"))) {
timestamp=jsonObject.get("timestamp").toString();
}
if (StrUtil.isEmptyIfStr(timestamp)) {
return new ValidateResponse(false, new CustomException(BaseResultInfoEnum.ERROR_MISSING_TIMESTAMP_1007.getMsg(), BaseResultInfoEnum.ERROR_MISSING_TIMESTAMP_1007.getCode()));
}
long now = System.currentTimeMillis();
long time = Long.parseLong(timestamp);
if (now - time > MAX_REQUEST) {
return new ValidateResponse(false, new CustomException(BaseResultInfoEnum.ERROR_TIMESTAMP_TIMEOUT_1008.getMsg(), BaseResultInfoEnum.ERROR_TIMESTAMP_TIMEOUT_1008.getCode()));
}
} catch (Exception e) {
e.printStackTrace();
}
return new ValidateResponse(true, null);
}
/**
* 校驗(yàn)返回對(duì)象
*/
private static class ValidateResponse {
private boolean validate;
private CustomException exception;
public ValidateResponse(boolean validate, CustomException exception) {
this.validate = validate;
this.exception = exception;
}
public boolean isValidate() {
return validate;
}
public Exception getException() {
return exception;
}
}
}
返回給前端(或其他平臺(tái)的)處理類
import comzzzz.xx.common.pojo.PageResponseModel;
import com.zzz.xxxx.common.pojo.ResponseModel;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @author sunrh
*/
@ControllerAdvice
public class ResponseBodyTimestamp implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//就是這里處理返回簽名數(shù)據(jù)
if(o instanceof ResponseModel){
ResponseModel responseModel= (ResponseModel) o;
responseModel.setTimestamp(System.currentTimeMillis());
return responseModel;
}
if(o instanceof PageResponseModel){
PageResponseModel responseModel= (PageResponseModel) o;
responseModel.setTimestamp(System.currentTimeMillis());
return responseModel;
}
return o;
}
}
最終實(shí)現(xiàn)的效果圖

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringBoot通過(guò)AOP與注解實(shí)現(xiàn)入?yún)⑿r?yàn)詳情
- SpringBoot使用AOP統(tǒng)一日志管理的方法詳解
- Springboot+AOP實(shí)現(xiàn)時(shí)間參數(shù)格式轉(zhuǎn)換
- springboot使用AOP+反射實(shí)現(xiàn)Excel數(shù)據(jù)的讀取
- SpringBoot中通過(guò)AOP整合日志文件的實(shí)現(xiàn)
- springboot利用AOP完成日志統(tǒng)計(jì)的詳細(xì)步驟
- SpringBoot中創(chuàng)建的AOP不生效的原因及解決
- 在springboot中使用AOP進(jìn)行全局日志記錄
- SpringBoot使用AOP實(shí)現(xiàn)統(tǒng)計(jì)全局接口訪問(wèn)次數(shù)詳解
相關(guān)文章
RocketMQ設(shè)計(jì)之主從復(fù)制和讀寫(xiě)分離
這篇文章主要介紹了RocketMQ設(shè)計(jì)之主從復(fù)制和讀寫(xiě)分離,RocketMQ提高消費(fèi)避免Broker發(fā)生單點(diǎn)故障引起B(yǎng)roker上的消息無(wú)法及時(shí)消費(fèi),下文關(guān)于了RocketMQ的相關(guān)內(nèi)容,需要的小伙伴可以參考一下2022-03-03
SpringBoot監(jiān)聽(tīng)器的實(shí)現(xiàn)示例
在SpringBoot中,你可以使用監(jiān)聽(tīng)器來(lái)響應(yīng)特定的事件,本文主要介紹了SpringBoot監(jiān)聽(tīng)器的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽(tīng)器)
這篇文章主要介紹了SpringBoot如何監(jiān)控Redis中某個(gè)Key的變化(自定義監(jiān)聽(tīng)器),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
IntelliJ IDEA(2019)安裝破解及HelloWorld案例(圖文)
這篇文章主要介紹了IntelliJ IDEA(2019)安裝破解及HelloWorld案例(圖文),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10
SpringBoot切面攔截@PathVariable參數(shù)及拋出異常的全局處理方式
這篇文章主要介紹了SpringBoot切面攔截@PathVariable參數(shù)及拋出異常的全局處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java利用Socket實(shí)現(xiàn)網(wǎng)絡(luò)通信功能
在早期的網(wǎng)絡(luò)編程中,Socket是很常見(jiàn)的實(shí)現(xiàn)技術(shù)之一,比如早期的聊天室,就是基于這種技術(shù)進(jìn)行實(shí)現(xiàn)的,另外現(xiàn)在有些消息推送,也可以基于Socket實(shí)現(xiàn),本文小編給大家介紹了Java利用Socket實(shí)現(xiàn)網(wǎng)絡(luò)通信功能的示例,需要的朋友可以參考下2023-11-11

