简体   繁体   中英

React native Axios Django - Csrf failed referer checking failed no referer

I am calling a Django back-end api from React front-end using axios.

For that api which is login api, I am using Django Knox package in logic.

React.js - I am calling axios.request(method, url, data) and the api call is working correctly. When I went to Developer tools > Network , I can see Referer header set to React.js website in request header and no other csrf-related header. In Response headers I can see two set-cookie headers, csrftoken and sessionid.

React Native - same way I am calling api but api returns error csrf failed referer checking failed - no referer . When I checked response.config , Referer header is not set unlike React.js

Curl - works fine

httpie - works fine

How can I get rid of this error.

Note 1 - My Django back-end is based on api token logic and not csrf in any way.

Note 2 - React.js and Django are hosted on different domains. I am facing error in React Native which is in debug mode.

Update 1 - After disabling CSRF middleware in Django settings.py, now I am getting only one setCookie header (csrftoken is no longer obtained) but same error still persists.

Django Rest api need a Referer header.

In case of React.js it is automatically set (maybe by browser) and its value is current website.

But in case of React Native, it is not set. so we have to manually set it.

  1. From this link , i set Referer header in axios. see below code
export const axiosAPICall = (method,url,data,headers) => {
    let request = {
        method: method,
        url: url,
    };
    if (data) {
        request['data'] = data;
    }
    if (headers) {
        request['headers'] = headers;
    }
    // Referer is auto-set in react.js as same website value.
    // for react-native we have to set it manually to target api:port
    request['headers'] = {
        ...request['headers'],
        Referer: url
    }
    return axios.request(request)
        .then(res => res.data)
        .catch(error => {throw error});
};
  1. In Django settings.py , I commented CSRF middleware
  2. In Django settings.py , I added only TokenAuthentication class to remove SessionAuthentication .
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

Note - Please do steps 2 and 3 at your risk after knowing your requirements properly. I removed CSRF middleware because my API was completely dependent on token for auth. I did not need CSRF in any way.

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