0

i import these two packages (csrf, cookieparser) and using inside the appjs for express only its working and also i tested in postman it's working fine here is my code express js:

const csrf = require('csurf')
const cookieParser = require('cookie-parser')

const csrfProtection = csrf({
    cookie: {
        httpOnly: true,
        maxAge: 3600
    }
});

app.use(cookieParser())
app.use(csrfProtection);

app.get('/auth/csrf-token', (req, res) => {
    res.json({ csrfToken: req.csrfToken() });
});

and also the frontend i using react js and inside the useEffect i fetch the csrf from backend after that i saved in the headers of the axios, but when i send request to the backend, response say invalid csrf :/

   useEffect(() => {
        const getCsrfToken = async () => {
            const { data } = await API.get('/auth/csrf-token');
            API.defaults.headers.post['X-CSRF-Token'] = data.csrfToken;
        };
        getCsrfToken();
    }, []);
    
      const handelLogin = (e) => {
        e.preventDefault();
        API.post('/auth/login', {
            headers: {
                'Content-Type': 'application/json'
            },
            data: { email, password },
        }).then(({ data }) => {

            if (data.token) {
                localStorage.setItem('token', data.token);
                window.location.href = '/admin'
            }

        }).catch((e) => {
            console.log(e)
        })
    }

the response from server: ForbiddenError: invalid csrf token;

  • this realy helped me i home it dose to someone else:) [React frontend and REST API, CSRF](https://stackoverflow.com/questions/45925344/react-frontend-and-rest-api-csrf) – Xpaew andX Jul 06 '22 at 10:22

2 Answers2

0

As mentioned in https://expressjs.com/en/resources/middleware/csurf.html#using-ajax

Try changing the header property to this,

API.defaults.headers.post['CSRF-Token'] = data.csrfToken;
Shri Hari L
  • 4,551
  • 2
  • 6
  • 18
0

I solve the problem by adding withcredentials to the axios all codes after changing

 AXIOS.get('get/csrf-token', {
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
            withCredentials: true
        }).then(({ data }) => {
            AXIOS.defaults.headers.common['x-csrf-token'] = data.csrfToken
            AXIOS.defaults.withCredentials = true
        })