Java 杂谈Spring-BootSpringboot整合

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

2018-09-19  本文已影响101人  垃圾简书_吃枣药丸

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("签名错误");
}

解决方案:采用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

用户权限拦截思路一致,看心情更新

上一篇 下一篇

猜你喜欢

热点阅读