Reputation: 93
I am tring to send csrf token by using axios post in react js but csrf token validation is failing. I am also done with credentials:true
but it's not working.I am receving csrf token in cookie but not able to send it.
class LoginService extends Component {
loginUser(formData)
{
const config = {
headers: { 'content-type': 'application/json',
'X-CSRFToken': Cookies.get("csrftoken")}
}
return axios.post(`${API_BASE_URL}api/user/v1/account/login_session/`,formData,config);
}
}
Upvotes: 0
Views: 3517
Reputation: 93
**This is how I solve my problem : first set these two as:- axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; **
loginUser(formData)
{
const config = {
headers: { 'content-type': 'application/json'},
"X-CSRFToken": Cookies.get('csrftoken'),
withCredentials: true
}
return axios.post(`${API_BASE_URL}api/user/v1/account/login_session/`,formData,config);
}
}
Upvotes: 0
Reputation: 13588
If you are using httpsOnly cookies then 'X-CSRFToken': Cookies.get("csrftoken")}
will not work.
What is HttpOnly?
According to the Microsoft Developer Network, HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it).
Using withCredentials: true
should suffice.
loginUser(formData)
{
const config = {
headers: { 'content-type': 'application/json' },
withCredentials: true
}
return axios.post(`${API_BASE_URL}api/user/v1/account/login_session/`,formData,config);
}
}
withCredentials indicates whether or not cross-site Access-Control requests should be made using credentials
withCredentials: false, // default
Of course you also need to ensure the cookie domain is set correctly in order for the cookie to work.
Tip: Check your chrome network inspector, and see whether the desire cookie is sent together with your request
If you are setting csrf cookie with httpOnly you can remove httpOnly.
There's an answer with regards to this here https://security.stackexchange.com/a/175540/135413
Upvotes: 1
Reputation: 1634
When you send the header in Axios to the server, you need to know if your server-side accepts the patterns: CSRF-TOKEN
or X-CSRF-TOKEN
or XSRF-TOKEN
or X-XSRF-TOKEN
.
You are using X-CSRFToken
, that not combine with any patterns shown above.
More here: https://www.npmjs.com/package/csurf
Upvotes: 1