简体   繁体   中英

Is it a good practice adding the CSRF token in redux store?

Is it a good practice to store a CSRF token in redux? I was passing it with props before (to add it to Axios headers). I have a rails back end and I am using the gem react-rails , my components are server rendered, so I did not come up with any other way of doing so but passing the CSRF token to the component.

It's fine to store the token in your Redux store.

The purpose of the token is to prevent other sites/origins from making non-GET (POST, PUT, DELETE) requests to your API. Without it, a malicious site could make the request and piggyback on the cookies and session stored in your browser. In a plain HTML server-rendered Rails app, this token is put directly into the HTML, making it available to any JavaScript on that page. So, it's not private information for any code on the pages you control.

Nonetheless, given it's global nature and that you might need it outside of the context of Redux, it's probably best to put it on window for anyone to use:

window.CSRF_TOKEN = document.querySelector("meta[name='csrf-token']").getAttribute("content")

Any time you call fetch , you can include these headers:

headers: {
 'X-CSRF-Token': window.CSRF_TOKEN
}

Since you're using react-rails , you can also pass it to your component as props:

react_component 'MyForm', authenticity_token: form_authenticity_token

If you're not relying on Rails sessions for authentication (with a Bearer token, for instance), you can also disable the CSRF token entirely with this line in your ApplicationController :

protect_from_forgery with: :null_session

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM