skip to Main Content

I have an Django project that runs on Apache. With Javascript and Python i make request on diffrent sites. I always get following error:

Access to XMLHttpRequest at 'site' from origin 'site2' has been blocked

I already tried diffrent things. I installed django-cors-headers and edited my files:

Settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'webpack_loader',
    'corsheaders',
    'projects',
    'viewer',
    'api_manager',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

In my HTML i added following to the form:

<form class="d-flex flex-column" id="loginForm">
          {% csrf_token %}
</form>

With the following method i was able to get a CSRF Token:

static getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
      let cookies = document.cookie.split(';');
      for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].trim();
        // Does this cookie string begin with the name we want?
        if (cookie.substring(0, name.length + 1) === (name + '=')) {
          cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
          break;
        }
      }
    }
    return cookieValue;
  }

And the call which needs CORS i already tried to add the correct Headers:

xhr.addEventListener('readystatechange', function () {
    if (this.readyState === 4) {
      if (this.status != 200) {
        console.log("Error", this.statusText);
      }
    }
  });

  xhr.onerror = function(e) {
    console.log("Error: " + e + "URL: " + url);
  }

  xhr.open(method, url, false);
  xhr.setRequestHeader('Authorization', auth);
  xhr.setRequestHeader('Content-Type', 'application/json');
  // xhr.setRequestHeader('Access-control-allow-origin', '*');
  xhr.setRequestHeader('Access-Control-Allow-Origin', '*');

  var token = Fetcher.getCookie('csrftoken');
  console.log(token);
  xhr.setRequestHeader('X-CSRFToken', token);
  xhr.send(data);

I dont know what I am missing. Does anyone know what i need to edit?

2

Answers


  1. Add this at the end of your settings.py file.

    CORS_ORIGIN_ALLOW_ALL = True
    
    Login or Signup to reply.
  2. Add these things, in your settings.py file as follows (if you haven’t added yet)…

    CORS_REPLACE_HTTPS_REFERER      = True
    HOST_SCHEME                     = "https://"
    SECURE_PROXY_SSL_HEADER         = ('HTTP_X_FORWARDED_PROTO', 'https')
    SECURE_SSL_REDIRECT             = True
    SESSION_COOKIE_SECURE           = True
    CSRF_COOKIE_SECURE              = True
    SECURE_HSTS_INCLUDE_SUBDOMAINS  = True
    SECURE_HSTS_SECONDS             = 1000000
    SECURE_FRAME_DENY               = True
    

    May be it’ll work for you. And, as you’ve added corsmiddleware to the middlewares you may check this guide once: django-cors-headers. Also, you can try with…

    CORS_ALLOW_HEADERS = [
        'accept',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
    ]
    CORS_ALLOW_METHODS = [
        'DELETE',
        'GET',
        'OPTIONS',
        'PATCH',
        'POST',
        'PUT',
    ]
    CORS_ORIGIN_REGEX_WHITELIST = [
        r"^https://w+.example.com$",
    ]
    

    Update with jquery…

    $(document).ready(function() {
        function getCookie(c_name) {
            if(document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=")
                if(c_start != -1) {
                    c_start = c_start + c_name.length + 1
                    c_end = document.cookie.indexOf(";", c_start)
                    if(c_end == -1) c_end = document.cookie.length
                    return unescape(document.cookie.substring(c_start,c_end))
               }
           }
           return ""
        }
    
        var csrfToken = getCookie('csrftoken')
    
        function csrfSafeMethod(method) {
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))
        }
    
        $(function () {
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader('X-CSRFToken', csrfToken)
                        xhr.setRequestHeader('Access-Control-Allow-Origin', '*')
                        xhr.withCredentials = true
                    }
                }
            })
            // .done(function (data) { *do something* })
            // .fail(function () { *do something* })
        })
     })
    
    

    I’m not sure though, either it’ll work for you or not, but you can try.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search