public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { if (accessDeniedException instanceof CsrfException && !response.isCommitted()) { // Remove the session cookie so that client knows it's time to obtain a new CSRF token String pCookieName = "CSRF-TOKEN"; Cookie cookie = new Cookie(pCookieName, ""); cookie.setMaxAge(0); cookie.setHttpOnly(false); cookie.setPath("/"); response.addCookie(cookie); } accessDeniedHandlerImpl.handle(request, response, accessDeniedException); }
@Override public void handle(final HttpServletRequest request, final HttpServletResponse response, final AccessDeniedException ex) throws IOException { response.setStatus(HttpServletResponse.SC_FORBIDDEN); final boolean sessionExists = request.getSession(false) != null; if (ex instanceof MissingCsrfTokenException) { LOG.warn("Missing CSRF token for requestURI={} for user {} with session={} and message: {}", request.getRequestURI(), getActiveUserInfo(), sessionExists, ex.getMessage()); } else if (ex instanceof CsrfException) { LOG.warn("Invalid CSRF token for requestURI={} for user {} with session={} and message: {}", request.getRequestURI(), getActiveUserInfo(), sessionExists, ex.getMessage()); } else { LOG.warn("Access denied for requestURI={} for user {} with exception {} message: {}", request.getRequestURI(), getActiveUserInfo(), ex.getClass().getName(), ex.getMessage()); } if (!response.isCommitted()) { response.setContentType("application/json"); response.getWriter().print("{\"status\": \"FORBIDDEN\"}"); response.getWriter().flush(); response.getWriter().close(); } }
@Bean public AccessDeniedHandler accessDeniedHandler() { LinkedHashMap<Class<? extends AccessDeniedException>, AccessDeniedHandler> handlers = new LinkedHashMap<>(); handlers.put(CsrfException.class, new CsrfTokenExceptionHandler()); return new DelegatingAccessDeniedHandler(handlers, new AccessDeniedHandlerImpl()); }