小编典典

有没有办法在使用Spring执行Rest API之前验证令牌

spring-boot

我已经为休息控制器配置了弹簧靴。我创建了许多api,但我需要在乞讨时在每个api中验证我的令牌信息,是否已授权用户使用提供的令牌。

在登录期间,我会生成令牌,该令牌是每个api中访问信息所需的令牌。如果令牌无效,那么我需要返回消息Sorry, your provided token information has been expired or not exists.

以下是我的API。

@RequestMapping(value="/delete", method= RequestMethod.DELETE)
public Map<String, Object> delete(@RequestBody String reqData,HttpServletRequest request) {
    Map<String, Object> m1 = new HashMap<String,Object>();
    JSONObject jsonData = new JSONObject(reqData);
    Token token= tokenDao.getByTokenCode(jsonData.getString("token"));
    if(token==null){
        m1.put("status", "error");
        m1.put("message", "Sorry, your provided token information expired or not exists.");
        return m1;
    }
    //here my logic to remove user from database.
}

有什么方法可以检查服务方法中的令牌功能或使用注释,因此我需要在每个api中删除相同的代码,并且需要使用一种通用功能。


阅读 445

收藏
2020-05-30

共1个答案

小编典典

您可以使用 HandlerInterceptor 来处理令牌。

HandlerInterceptor.preHandle(HttpServletRequest请求,HttpServletResponse响应,对象处理程序)
将在任何RequestMapping之前执行。

preHandle中 验证您的令牌。如果令牌有效,则继续,否则抛出异常,控制器建议将处理其余部分。

公开MappedInterceptor的bean类,spring会自动加载Bean中包含的HandlerInterceptor。

ControllerAdviceExceptionHandler 可以捕获异常并返回错误消息

完整的例子

@RestController
@EnableAutoConfiguration
public class App {

    @RequestMapping("/")
    public String index() {
        return "hello world";
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    public static class MyException extends RuntimeException {

    }

    @Bean
    @Autowired
    public MappedInterceptor getMappedInterceptor(MyHandlerInterceptor myHandlerInterceptor) {
        return new MappedInterceptor(new String[] { "/" }, myHandlerInterceptor);
    }

    @Component
    public static class TestBean {
        public boolean judgeToken(HttpServletRequest request) {
            String token = request.getParameter("token");
            if (token == null) {
                throw new MyException();
            }
            return true;
        }
    }

    @Component
    public static class MyHandlerInterceptor implements HandlerInterceptor {

        @Autowired
        TestBean testBean;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            return testBean.judgeToken(request);
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {

        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                Exception ex) throws Exception {

        }
    }

    @ControllerAdvice
    public static class MyExceptionHandler {
        @ExceptionHandler(MyException.class)
        @ResponseBody
        public Map<String, Object> handelr() {
            Map<String, Object> m1 = new HashMap<String, Object>();
            m1.put("status", "error");
            m1.put("message", "Sorry, your provided token information expired or not exists.");
            return m1;
        }
    }

}
2020-05-30