简体   繁体   中英

403 Forbidden request when making an axios call with React (Django backend)

I am trying to authenticate my session on a web application using ReactJS. My backend is setup on Django. When logging in to the application, I do receive the cookies in the header, however I am unable to set the cookies. However, when I try to post the request 'withCredentials: true', it returns me the 403 error.

The login call (Where I receive the cookies in response header)

let url = `${BASE_URL}/login/`;
    console.log('params for validateOtp:', params);
    axios
      .post(url, params)
      .then((res) => {
        console.log('validate otp code res: ', res);
        resolve(res);
      })
      .catch((err) => {
        console.log('validate otp code err: ', err);
        reject(err);
      });

After seeing the console, it is visible under the 'Network' tab that I do receive cookies from this API.

This is the API where I make the authenticated call.

let url = `${BASE_URL}/updatemerchant/`;
    axios
      .post(url, params, {
        withCredentials: true
      }
      )
      .then((res) => {
        console.log('updateDukaanUserToCloud res : ', res);
        // resolve(res)
        if (res.status === 200) {
          resolve(res);
        } else {
          reject('updateDukaanUserToCloud something went wrong');
        }
      })
      .catch((err) => {
        if (err.response && err.response.status === 400) {
          reject('updateDukaanUserToCloud updating user info failed');
        } else {
          reject('updateDukaanUserToCloud something went wrong');
        }
      });

settings.py

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_NAME = "csrftoken"
CORS_ORIGIN_WHITELIST = ('http://localhost:3000', 'http://127.0.0.1:3000', 'localhost:3000', '127.0.0.1:3000')
CSRF_TRUSTED_ORIGINS = [
    'localhost:3000',
    '127.0.0.1:3000',
] 

The error I receive with the 403 forbidden request.

CSRF Token, as of this point, should not be a problem, since you cannot get past the authentication problem. If Django "Session authentication" is correctly installed, whenever the correct credentials are passed from React, and "login" method is called in Django, it should automatically attach the session cookie and you don't need to do additional work in React.

Did you add the "django.contrib.sessions.middleware.SessionMiddleware" middleware?

PS You will need to attach CSRF Token if you want to use POST requests afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM