Django API, React frontend, and CSRF protections

Hi everyone, front-end guy here with some questions about security, specifically about csrf attacks and how Django can help stop them. Our project consists of a React app that will be making requests to our API that we're building with Django. I've been reading about csrf attacks and want to make sure our API is set up with the proper security in place.

My understanding is that properly setting our CORS policy is NOT a proper substitute for correctly configuring our API against csrf attacks. My research led me to two possible answers; I'm hoping people here can give me a bit of guidance to know if I'm on the right track.

The first solution I saw is discussed [here on StackOverflow](, actually in the comments of the question not the answers. Someone makes the suggestion to create "a dedicated CSRF endpoint" to fetch a csrf token, which React can then store and use in all the requests it needs to make to the API. This appeals to me because we need to let un-authenticated users make at least one POST request in our app.\* Is this really a valid solution though? Maybe I don't understand csrf attacks well, but my intuition is that if someone can just make a request to get a token then how does that stop them from making malicious requests with that token?

The second option seems to be a value in our `` file. It looks like there is a CSRF\_TRUSTED\_ORIGINS value that we can give a list of "hosts which are trusted origins for unsafe requests". If we give this a list of domains, like with our CORS whitelist, will that give us the protection that we need?

As you can tell, this is a new topic for me. Thanks in advance for your help!

\*The site contains user-generated content, and we don't want to stop people from "flagging" content as inappropriate if they're not logged in. Allowing un-authenticated users to make a POST request that contains the reason(s) they're flagging content might not be a good idea. I'm open to other approaches, however, I still want to make sure I'm understanding the proper way to stop csrf attacks with Django.

1 thought on “Django API, React frontend, and CSRF protections”

Leave a Comment