Is there any way to validate token before executio

2019-06-21 18:52发布

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.

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.

below is the my 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.
}

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.

3条回答
对你真心纯属浪费
2楼-- · 2019-06-21 19:22

you can use HandlerInterceptor to handle you token.

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

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

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

ControllerAdvice and ExceptionHandler can catch exception and return error message

full example

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

}
查看更多
劳资没心,怎么记你
3楼-- · 2019-06-21 19:28
public class TokenVallidation
 {        
    public static boolean tokenValidation(user id, String token){    
        Token token= tokenDao.getByTokenCode(id,jsonData.getString("token"));
        if(token==null){
            m1.put("status", "error");
            m1.put("message", "Sorry, your provided token information expired or not exists.");
            return false;
        }     
        else{
            return true;
        }
    }
}

for controller pass user id and token and check the token. you need to update dao method as per user id parameter.

查看更多
4楼-- · 2019-06-21 19:36

Instead of getting token from database and matching with current token you can use cache. create your own cache object like Map or a static string, which will have the latest token. and you can direct compare incoming token with this token from cache. no need to hit database for every time.

查看更多
登录 后发表回答