@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { // When missing or providing an invalid CSRF token we will prompt a challenge. if (accessDeniedException instanceof InvalidCsrfTokenException) { final HttpSession session = request.getSession(false); if (session == null) { throw new IllegalStateException("Cannot create CSRF token challenge when session is null."); } final String token = (String) session.getAttribute(CSRFTokenCheck.CSRF_TOKEN_ATTRIBUTE_NAME); response.setHeader(ERRAI_CSRF_TOKEN_HEADER, token); } super.handle(request, response, accessDeniedException); }
/** * https://docs.spring.io/spring-security/site/docs/4.2.3.RELEASE/reference/htmlsingle/#csrf-timeouts * https://stackoverflow.com/questions/32446903/what-is-the-best-way-to-handle-invalid-csrf-token-found-in-the-request-when-sess */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { LOGGER.warn("{},{},{}", Flag.BizLogFlag.WARN_CHECK, RequestHolder.getLastAccessUri(), accessDeniedException.getClass().getCanonicalName()); if (accessDeniedException instanceof MissingCsrfTokenException || accessDeniedException instanceof InvalidCsrfTokenException) { response.sendRedirect("/"); } }
@Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException { if (authException instanceof InvalidCsrfTokenException || authException instanceof MissingCsrfTokenException) { response.setHeader(CsrfHeaders.CSRF_TOKEN_HEADER, CSRF_TOKEN_REQUIRED_HEADER_VALUE); } doHandle(request, response, authException); }
@Override public void handle( HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException ) throws IOException, ServletException { if (accessDeniedException instanceof InvalidCsrfTokenException || accessDeniedException instanceof MissingCsrfTokenException) { new DefaultRedirectStrategy().sendRedirect(request, response, "/editar/autenticar?sessao"); } super.handle(request, response, accessDeniedException); }
@Test public void redirecionaParaAutenticacaoQuandoTokenCsrfÉInvalido() throws Exception { AccessDeniedException exception = new InvalidCsrfTokenException( new DefaultCsrfToken("header", "param", "token"), "actualToken" ); handler.handle(request, response, exception); assertThat(response.getRedirectedUrl(), is("/editar/autenticar?sessao")); }