栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

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

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

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

完整的例子

@RestController@EnableAutoConfigurationpublic 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;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/379279.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号