Httpsessioncsrftokenrepository

Here’s an example code for Spring Boot using HttpSessionCsrfTokenRepository to prevent duplicate requests for charging points on a web novel service:

  1. Configure Spring Security to use HttpSessionCsrfTokenRepository:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
     @Override
     protected void configure(HttpSecurity http) throws Exception {
         http
             .csrf()
                 .csrfTokenRepository(new HttpSessionCsrfTokenRepository());
     }
    }
    
  2. Create a controller to expose an endpoint for fetching the CSRF token:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    @RestController
    public class CsrfTokenController {
    
     @GetMapping("/csrf-token")
     public ResponseEntity<Void> getCsrfToken(HttpServletRequest request, HttpServletResponse response) {
         CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    
         if (csrfToken != null) {
             response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());
             return ResponseEntity.ok().build();
         } else {
             return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
         }
     }
    }
    

About your explanation “The filter checks if a CSRF token exists in the session for the current user”, does the “session for the current user” mean “httpSession of the current user” ?

Yes, that’s correct. The “session for the current user” refers to the HttpSession associated with the current user. Each user has a unique HttpSession when they interact with a web application, and this session is maintained on the server-side to store user-specific information, like CSRF tokens.

When I mentioned “the filter checks if a CSRF token exists in the session for the current user,” it means that the filter checks the HttpSession of the current user to see if a CSRF token is already present. If not, it creates one using HttpSessionCsrfTokenRepository and stores it in the user’s session.

comments powered by Disqus