CSRF token expires during login

前端 未结 4 2490
挽巷
挽巷 2021-02-01 08:57

I\'m working on Spring web application and I need to avoid problem with expire csrf token on login page, because if user is waiting too long and try to login only one way to res

4条回答
  •  面向向阳花
    2021-02-01 09:23

    In one of the projects I worked on, I implemented the following:

    1. Implement an exception handler which handles CsrfException (or AccessDeniedException in general in my case). Forward the request to a controller method.

      @ExceptionHandler(AccessDeniedException.class)
      @ResponseStatus(value = HttpStatus.FORBIDDEN)
      public void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
          request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
          request.getRequestDispatcher("/Access_Denied").forward(request, response);
      }
      
    2. In the controller method, check whether the original request is for the login page. If so, show an appropriate message within the login page.

      if ("/login".equals(request.getAttribute(RequestDispatcher.FORWARD_SERVLET_PATH))) {
          model.addAttribute("error", "An invalid security token has been detected. Please try again.");
          return "login.jsp";
      } else {
          return "accessDenied.jsp";
      }
      

    With this approach, user will be able to retry the login without the need to refresh.

提交回复
热议问题