concept csrf token in category spring

This is an excerpt from Manning's book Spring Security in Action MEAP V07.
For the first time, we’ll write endpoints that can be called with another HTTP method than GET. You might have observed that until now, I’ve avoided using other HTTP methods than GET. The reason why I have avoided doing this is that Spring Security applies by default protection against Cross-Site Request Forgery (CSRF). In chapter 1, I have described CSRF, which is one of the most common vulnerabilities for web applications. Cross-Site Request Forgery was for a long time present in the OWASP Top 10. In chapter 10, we’ll discuss how Spring Security mitigates this vulnerability by using CSRF tokens. But to make things simpler for the current example and be able to call all the endpoints, including those exposed with POST, PUT or DELETE, we will have to disable the CSRF protection.
The application now accepts only requests for mutating operations (POST, PUT, DELETE, etc.) that contain this unique value in the header. The application considers that knowing the value of the token is proof that it is the app itself making the mutating request and not another system. Any page containing mutating calls, like POST, PUT, DELETE etc, should receive through the response the CSRF token, and the page must use this token when making the mutating calls.
Figure 10.2 To make a POST request, the client needs to add a header containing the CSRF token. The application generates a CSRF token when the page is loaded (via a GET request), and the token is added to all the requests that could be done from the loaded page. This way, only the page loaded can make mutable requests.
![]()
In the definition of the controller class presented in listing 10.20, we also add an endpoint that uses the HTTP GET method. We need this method to obtain the CSRF token when testing our implementation firstly.
@GetMapping("/hello") public String getHello() { return "Get Hello!"; }You can now start the application and test the new implementation for token management. We call the endpoint using HTTP GET to obtain a value for the CSRF token. When making the call, we have to use an identifier of the client within the X-IDENTIFIER header as assumed from the requirement. A new value of CSRF token is generated and stored in the database.
curl -H "X-IDENTIFIER:12345" http://localhost:8080/hello Get Hello!We search in the token table in the database and find that the application added a new record for the client with identifier 12345. In my case, the generated value for the CSRF token, which I can see in the database, is 2bc652f5-258b-4a26-b456-928e9bad71f8. We use this value to call the /hello endpoint with the HTTP POST method, as presented in the next code snippet. Of course, we have to provide also the identifier for the client, used by the application to retrieve the token from the database to compare with the one we provide in the request.