Code_Breaker
Code_Breaker

Reputation: 93

Axios post fails with 403 error code and showing CSRF token validation failed but works fine django api when passing csrftoken in header with Postman

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

Answers (3)

Code_Breaker
Code_Breaker

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

Someone Special
Someone Special

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

CSRF with HttpOnly

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

Cássio Lacerda
Cássio Lacerda

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

Related Questions