1

I'm doing a project for my class and we're required to make a secure login feature..something I haven't done before.. I'm trying to store the csrfToken in a header so it shows up as my session token in cookies but I'm not sure I'm doing it right.If anyone could help, I'd be very grateful. I know this is probably an easy fix but I've looked everywhere and haven't got it yet.

getToken = () => {

    axios({
        method: 'get',
        url: '/csrf',
        timeout: 1000,
        headers: 'csrf-token'
    }).then(csrfToken => {
        console.log(csrfToken);
        this.setState({ accessGranted: true })
    }).catch(err => console.log(err));
}

I'm getting a response in the console but it's not storing it in the cookies.

walkforr
  • 47
  • 1
  • 5
  • If I understood you correctly you need to pass the `csrfToken` each and everytime you call an api - Is it so? or storing the csrfToken in cookie is enough? – Aamin Khan Dec 09 '18 at 16:02
  • yes, how would i pass the csrfToken each and everytime i call an api?: – walkforr Dec 09 '18 at 16:08

1 Answers1

1

You can use react-cookies:

import cookie from 'react-cookies'

and save your cookie like this:

cookie.save('csrftoken', csrfToken);

Then you can use it whenever you want.

Hadi Ranjbar
  • 1,692
  • 4
  • 21
  • 44
  • Okay and what is the other way? to pass the csrfToken each and everytime you call an api – walkforr Dec 09 '18 at 16:07
  • You can access the token with `const token = cookie.get('csrftoken');` and then you can pass it to axios as a header? `axios.get( url, {headers: { "name" : "value" } } ) .then((response) => { // other code );` – Predrag Beocanin Dec 09 '18 at 16:12
  • @walkforr the specific name of the header and method of passing it would depend on the backend. Also, you may or may not want to consider `localStorage` as something where you would save your token. It's a simple as `localStorage.setItem('name', value)` and `localStorage.getItem('name')` – Predrag Beocanin Dec 09 '18 at 16:13
  • And here's a bit of text about localStorage vs cookies, in case you care: https://stackoverflow.com/questions/3220660/local-storage-vs-cookies – Predrag Beocanin Dec 09 '18 at 16:14
  • If you want to automatically pass the header at each request you can use axios request interceptors. – Hadi Ranjbar Dec 09 '18 at 16:18
  • Yes you can use axios interceptor to pass it in each and every time when you call the api, something like this `axios.defaults.headers.common['Authorization'] = csrftoken ` – Aamin Khan Dec 09 '18 at 16:23
  • You actually should not pass a CSRF token in a cookie. That's the whole point of a CSRF token. See OWASP guide here. https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html – brycejl May 12 '21 at 18:45