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;