[API] "Can't verify CSRF token authenticity" when attempting to update avatar for user

AI-generated summary

rxmie is experiencing an issue with updating a user’s avatar via the API, receiving a “Can’t verify CSRF token authenticity” error. The error occurs both locally and on the server, and is not related to load balancer or proxy issues. The user has provided server logs and the API request code, showing a 422 Unprocessable Entity response. Similar issues have been reported by others in the past (1, 2).

Similar issue here - Cant update email via API - invalid_access error

What I see on the server logs:

Started PUT "/u/brodie-16/preferences/avatar/pick.json" for 24.17.99.993 at 2022-09-08 10:28:10 +0000
Processing by UsersController#pick_avatar as JSON
  Parameters: {"upload_id"=>13, "type"=>"uploaded", "username"=>"pelican-16", "user"=>{}}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 34ms (Views: 0.3ms | ActiveRecord: 0.0ms | Allocations: 6549)

Request I’m making:

import requests
import json

url = "https://blah.blahblah.blah/u/brodie-16/preferences/avatar/pick.json"

payload = json.dumps({
  "upload_id": 13,
  "type": "uploaded"
})
headers = {
  'Api-Key': 'blahblahblahblahhhhh',
  'Api-Username': 'system',
}

response = requests.request("PUT", url, headers=headers, json=payload)

print(response.text)

Response I’m getting from the API:

{
    "failed": "FAILED"
}

I know it’s not load balancer/proxy related because it doesn’t even work locally from the instance I’m running Discourse on.

[root@ip-10-say-whatt-2 discourse]# curl --insecure --location --request PUT 'https://localhost/u/brodie-16/preferences/avatar/pick.json' \
> --header 'Api-Key: blahblah' \
> --header 'Api-Username: system' \
> --header 'Content-Type: application/json' \
> --data-raw '{
>     "upload_id": 13,
>     "type": "uploaded"
> }'
{"failed":"FAILED"}

Someone else posted this recently as well - Can't verify CSRF token authenticity while creating topics

Anyone know what’s going on ?