Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to validate token before execution of rest api using spring

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.

like image 888
Mehul Dudhat Avatar asked Dec 14 '22 08:12

Mehul Dudhat


1 Answers

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

}
like image 99
wcong Avatar answered Jan 15 '23 03:01

wcong