动态验签与用户权限拦截(Spring HandlerInterceptor)

简介: 动态验签与用户权限拦截(Spring HandlerInterceptor)
  • 在对接第三方的时候,为了保证数据的安全性,双方会约定在请求的参数中加上一些签名之类的信息,比如把接口请求的参数排序之后进行加密再比较双方加密的信息是否一致。


eg: 请求地址 http://localhost:8888/userinfo/get?usercode=123&timestamp=123&sign=123

HashMap<String,String> map=new HashMap<>();
  map.put("usercode","123");
  map.put("timestamp","123");
  map.put("sign","123");
  String signResult=SignatureService.sign(map);
  if(!signResult.equal(sign)){
     log.error("签名错误");
}
  • 1.为了避免在每个对接的方法中都进行上面重复的签名校验
  1. 为了避免之后参数有改动,而要修改逻辑代码(map.put()),所以需要实现参数的动态验证(即:动态读取请求的参数进行参数的加密校验)


解决方案:采用spring HandlerInterceptor对请求进行拦截

SpringBoot (v2.0.5.RELEASE)


  1. 定义需要进行参数加密校验的标记注解

package com.futao.springmvcdemo.annotation;
import java.lang.annotation.*;
/**
 * @author futao
 * Created on 2018/9/18-14:46.
 * 需要验证签名的注解
 */
@Target(value = {
        ElementType.TYPE,
        ElementType.METHOD
})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Sign {
}
  1. 定义拦截被标注了该注解的拦截器

package com.futao.springmvcdemo.annotation.impl;
import com.futao.springmvcdemo.annotation.Sign;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author futao
 * Created on 2018/9/18-14:49.
 * springmvc拦截器适配器,或者实现HandlerInterceptor
 */
@Component
public class SignInterceptor extends HandlerInterceptorAdapter {
    /**
     * 请求到达controller之前
     *
     * @param request
     * @param response
     * @param handler
     * @return true继续执行controller,false不执行controller
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            Sign signAnnotation = ((HandlerMethod) handler).getMethodAnnotation(Sign.class);
            //获取请求数据
            String queryString = request.getQueryString();
            //请求的方法被标记了@Sign注解,并且请求的参数不为空
            if (ObjectUtils.allNotNull(signAnnotation) && ObjectUtils.allNotNull(queryString)) {//需要对参数进行加密校验
                for (String kv : queryString.split("&")) {
                    int charIndex = kv.indexOf("=");
                    System.out.println("key: " + kv.substring(0, charIndex));
                    System.out.println("value: " + kv.substring(charIndex));
                }
            }
        }
        return true;
    }
}
  1. 注册该拦截器

package com.futao.springmvcdemo.annotation;
import com.futao.springmvcdemo.annotation.impl.SignInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
 * @author futao
 * Created on 2018/9/18-15:15.
 */
@SpringBootConfiguration
public class WebMvcConfiguration implements WebMvcConfigurer {
    @Resource
    private SignInterceptor signInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //  "/**"和"/*"是有区别的
        registry.addInterceptor(signInterceptor).addPathPatterns("/**");
    }
}

4.在controller中使用该注解

package com.futao.springmvcdemo.controller;
import com.alibaba.fastjson.JSONObject;
import com.futao.springmvcdemo.annotation.Sign;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author futao
 * Created on 2018/9/18-17:15.
 */
@RestController
@RequestMapping(path = "World", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class WorldController {
    @Sign
    @RequestMapping(value = "post", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject post(
            @RequestParam("name") String name,
            @RequestParam("password") String password,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("appkey") String appkey,
            @RequestParam("sign") String sign
    ) {
        JSONObject object = new JSONObject();
        object.put("code", 0);
        object.put("result", "请求成功");
        return object;
    }
}


5.测试

请求地址:http://localhost:8080/Hello/post?name=Niubi1&password=Lihai&timestamp=1387113121&appkey=Yyalk23&sign=231

结果:


image.png

相关文章
|
Java 数据库 Spring
Spring Boot 实现定时任务的动态增删启停
Spring Boot 实现定时任务的动态增删启停
314 0
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
779 0
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——拦截自定义异常
本文介绍了在实际项目中如何拦截自定义异常。首先,通过定义异常信息枚举类 `BusinessMsgEnum`,统一管理业务异常的代码和消息。接着,创建自定义业务异常类 `BusinessErrorException`,并在其构造方法中传入枚举类以实现异常信息的封装。最后,利用 `GlobalExceptionHandler` 拦截并处理自定义异常,返回标准的 JSON 响应格式。文章还提供了示例代码和测试方法,展示了全局异常处理在 Spring Boot 项目中的应用价值。
801 0
|
前端开发 Java Spring
关于spring mvc 的 addPathPatterns 拦截配置常见问题
关于spring mvc 的 addPathPatterns 拦截配置常见问题
971 2
|
安全 Java 应用服务中间件
如何在 Spring Boot 3.3 中实现请求 IP 白名单拦截功能
【8月更文挑战第30天】在构建Web应用时,确保应用的安全性是至关重要的。其中,对访问者的IP地址进行限制是一种常见的安全措施,特别是通过实施IP白名单策略,可以只允许特定的IP地址或IP段访问应用,从而有效防止未授权的访问。在Spring Boot 3.3中,我们可以通过多种方式实现这一功能,下面将详细介绍几种实用的方法。
1648 1
|
安全 Java 数据安全/隐私保护
Spring 安全配置中拦截 URL 的顺序重要性
【8月更文挑战第21天】
391 1
|
开发框架 自然语言处理 Java
如何在Spring Boot中实现动态多语言支持
如何在Spring Boot中实现动态多语言支持
2485 3
|
Java 测试技术 开发者
【亮剑】通过自定义注解实现Spring AOP,可以更灵活地控制方法拦截和增强
【4月更文挑战第30天】通过自定义注解实现Spring AOP,可以更灵活地控制方法拦截和增强。首先定义自定义注解,如`@MyCustomAnnotation`,然后创建切面类`MyCustomAspect`,使用`@Pointcut`和`@Before/@After`定义切点及通知。配置AOP代理,添加`@EnableAspectJAutoProxy`到配置类。最后,在需拦截的方法上应用自定义注解。遵循保持注解职责单一、选择合适保留策略等最佳实践,提高代码可重用性和可维护性。记得测试AOP逻辑。
763 1
|
Java 数据库 Spring
Spring Boot 实现定时任务的动态增删启停
Spring Boot 实现定时任务的动态增删启停
256 1
|
Java Nacos 网络架构
Spring Cloud gateway 网关四 动态路由
Spring Cloud gateway 网关四 动态路由