Created
November 29, 2015 22:41
-
-
Save khamiltonuk/0e5e32c61fb9103535c6 to your computer and use it in GitHub Desktop.
Write annotation and a request interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; | |
| public class SecureTokenInterceptor extends HandlerInterceptorAdapter { | |
| private SecureTokenService secureTokenService; | |
| /** | |
| * Constructor. | |
| * | |
| * @param secureTokenService - service to store/retrieve tokens | |
| */ | |
| public SecureTokenInterceptor( | |
| SecureTokenService secureTokenService) { | |
| this.secureTokenService = secureTokenService; | |
| } | |
| @Override | |
| public boolean preHandle(HttpServletRequest req, | |
| HttpServletResponse resp, | |
| Object handler) throws Exception { | |
| HandlerMethod method = (HandlerMethod) handler; | |
| SecureToken secureToken = | |
| method.getMethodAnnotation(SecureToken.class); | |
| if (secureToken != null | |
| && RequestMethod.POST | |
| == RequestMethod.valueOf(req.getMethod())) { | |
| return checkValidToken(req, resp, secureToken); | |
| } | |
| return true; | |
| } | |
| private boolean checkValidToken(HttpServletRequest req, | |
| HttpServletResponse resp, | |
| SecureToken secureToken) | |
| throws IOException, ModelAndViewDefiningException { | |
| String tokenValue = | |
| req.getParameter(SecureToken.TOKEN_PARAMETER_NAME); | |
| if (StringUtils.isEmpty(tokenValue)) { | |
| resp.sendError(400); | |
| // Bad page setup or someone is messing with us | |
| return false; | |
| } else if (!secureTokenService.checkToken( | |
| secureToken.value(), tokenValue)) { | |
| ModelAndView mav = | |
| new ModelAndView("redirect:/page-expired"); | |
| throw new ModelAndViewDefiningException(mav); | |
| } | |
| return true; | |
| } | |
| @Override | |
| public void postHandle(HttpServletRequest req, | |
| HttpServletResponse resp, | |
| Object handler, | |
| ModelAndView modelAndView) | |
| throws Exception { | |
| HandlerMethod method = (HandlerMethod) handler; | |
| SecureToken secureToken = | |
| method.getMethodAnnotation(SecureToken.class); | |
| if (secureToken != null) { | |
| String tokenValue = secureTokenService | |
| .getOrGenerateToken(secureToken.value()); | |
| modelAndView.addObject( | |
| SecureToken.TOKEN_PARAMETER_NAME, tokenValue); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment