I know this issue crops up a lot but I have yet to find a secure solution.(Note I have anonymised the urls below.)
Problem:
- I have set up a Apache server running Django as a restful API on serverA
- on serverB I have a simple jquery AJAX GET request
- When the request is sent I get a "No 'Access-Control-Allow-Origin' header" Error but the origin is in the cors whitelist
Notes:
- I have installed Cors Headers in Django as per https://pypi.org/project/django-cors-headers/
- I have added serverB's url to CORS_ORIGIN_WHITELIST
- If I set CORS_ORIGIN_ALLOW_ALL = True it works fine (but insecure)
- Opening the url directly gives me the correct json response
Code:
Jquery on ServerB:
getValueWithKey : function(table, key, callback){
uri = "serverA.com/{0}/{1}".format(table, key)
$.ajax({
url: uri,
type:"GET"
crossDomain: true,
dataType: 'json'
}).done(function(data) {
console.log(data);
callback(data);
});
},
Headers(As per chrome console):
General:
Request URL: http://serverA.com/tablename/keyname
Request Method: GET
Status Code: 200 OK
Remote Address: serverA.com
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Content-Type: application/json
Request Headers:
!Provisional headers are shown
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://serverB.com
Referer: http://serverB.com/test.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Thanks for the help!
asked Aug 22, 2018 at 13:26
SBUK-Tech
1,4251 gold badge16 silver badges33 bronze badges
2 Answers 2
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
INSTALLED_APPS = [
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
]
Sign up to request clarification or add additional context in comments.
1 Comment
SBUK-Tech
Thanks marin but I needed the more secure setup without CORS_ORIGIN_ALLOW_ALL . FYI I found the issue which I have shown in answer.
Turns out I needed to change:
CORS_ORIGIN_WHITELIST=('http://example.net')
to
CORS_ORIGIN_WHITELIST=('example.net')
answered Sep 5, 2018 at 13:58
SBUK-Tech
1,4251 gold badge16 silver badges33 bronze badges
Comments
lang-js
Access-Control-Allow-Origin : *, so you are probably not setting your cors correctly on the server side.