Home > Software engineering >  Curl lets me GET but does not let me POST ... Spring JPA
Curl lets me GET but does not let me POST ... Spring JPA

Time:08-30

When I run the Spring Application and then try to comunicate with the REST API it allows me to GET but not to POST.

So this works:

curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b http://localhost:5000/activity/getall

This does not work:

curl -u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b
-H "Accept: application/json" 
-X POST 
-d '{
    "name":"Sleep",
    "criteria":"Sleep at least 8 hrs",
    "ini":"2022-08-30",
    "periodicity":"DAY",
    "periodicityCount":"1"
    }'
http://localhost:5000/activity/post

If you notice is the same Username and Password.

This is the response I get:

HTTP/1.1 403 
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json
Transfer-Encoding: chunked
Date: Mon, 29 Aug 2022 19:25:27 GMT
Connection: close

{
  "timestamp": "2022-08-29T19:25:27.510 00:00",
  "status": 403,
  "error": "Forbidden",
  "path": "/activity/post"
}

CodePudding user response:

The reason why your API calls fail is due to the CSRF protection you enabled in your Spring Security configuration.

The way this works is that for each non-GET request (= POST, PUT, PATCH or DELETE), you need to include a CSRF token.

To obtain a CSRF token, you first need to fire a GET request (eg. http://localhost:5000/activity/getall). In the response headers, you should see a Set-Cookie header containing an XSRF-TOKEN cookie. For example:

Set-Cookie: XSRF-TOKEN=098b732a-282a-11ed-a261-0242ac120002

Now you need to copy the value of the XSRF-TOKEN cookie (should contain a UUID), and set it as the value of the X-XSRF-TOKEN header:

curl \
-u user:a75fd7ea-9a6e-4943-bc0c-3b0a96bda51b
-H "Accept: application/json"
-H "X-XSRF-TOKEN: 098b732a-282a-11ed-a261-0242ac120002"
-X POST \
-d '{
    "name":"Sleep",
    "criteria":"Sleep at least 8 hrs",
    "ini":"2022-08-30",
    "periodicity":"DAY",
    "periodicityCount":"1"
    }'
http://localhost:5000/activity/post

After that, your request should succeed. Be aware, the response of this POST-request will contain a new CSRF token that you will have to copy to your next request.

Alternatively, you can disable CSRF protection by setting .csrf().disable() in your Spring Security configuration.

  • Related