有没有办法在使用spring执行rest api之前验证令牌 [英] Is there any way to validate token before execution of rest api using spring

查看:34
本文介绍了有没有办法在使用spring执行rest api之前验证令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为rest控制器配置了spring boot.我创建了许多 api,但我需要在请求时验证每个 api 中的令牌信息,用户是否基于提供的令牌获得授权.

I have configured spring boot for rest controller. I created many api but i need to validate my token information in every api at begging, Is user is authorized or not base on provided token.

在登录期间,我正在生成令牌,该令牌在每个 api 中都需要用于访问信息.如果令牌无效,则我需要返回消息 对不起,您提供的令牌信息已过期或不存在.

During the signin i am generating token that token required in every api for accessing information. if token is not valid then i need to return message 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 中删除相同的代码并需要使用一个通用功能.

Is there any way to check token functionality in service method or using annotation, so i need to remove that same code in every api and need to use one common functionality.

推荐答案

您可以使用 HandlerInterceptor 来处理您的令牌.

you can use HandlerInterceptor to handle you token.

HandlerInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 将在任何 RequestMapping 之前执行.

HandlerInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) will execute before any RequestMapping.

preHandle中验证你的令牌.如果令牌有效继续,否则抛出异常,控制器通知将处理其余的.

validate you token in preHandle.if token is valid continue,else throw exception,controller advice will handler the rest.

暴露MappedInterceptor的bean类,spring会自动加载HandlerInterceptor bean所包含的.

expose bean class of MappedInterceptor,spring will auto load HandlerInterceptor bean contains.

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

ControllerAdvice and ExceptionHandler can catch exception and return error message

完整示例

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

}

这篇关于有没有办法在使用spring执行rest api之前验证令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆