I'm building an AngularJS app with Django Rest Framework and Django CORS Headers as backend API.
Everything was working fine until today. Suddenly the csrfcookie and sessionid cookie stopped showing up in Chrome.
I see the API responding to me with the csrfcookie. Chrome doesn't show it in dev tools, however I see it in chrome://settings/cookies.
AngularJS
$httpProvider.defaults.useXDomain = true;
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$http({withCredentials: true, ...})
Django API
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'X-CSRFToken'
)
Ok so the answer to this issue is quite simple but not always very easy to notice since there are no error messages from the API, nor the client.
The problem above is that I reside on domain.com in my browser, but my request is towards the API is to "www.domain.com:8000". Both www.domain.com and domain.com are allowed origins in my API.
Conclusion here is that if I reside on domain.com then I need to make my API request towards domain.com:8000. But if reside on www.domain.com in my browser, then I need to make my API request towards www.domain.com:8000.
Se a working example down bellow:
Cookies now appear fine!
I hope this helps anyone, saving a few hours of frustration :)
Update:
Enabling the following settings in the Django settings file will also solve the problem. Using them let's you reside on different subdomains in your browser, and the cookies will return for domain ".domain.com"
https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-domain
https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-domain
Thanks to apollo on irc.freenode.net, #django for the updated answer.
Related
I am using django 3.2 , i had implemented csrf using below link
Link
Everything works fine when using same domain for client and server.
But while testing locally i get the error when sending post, put or delete requests.
I can see csrftoken in the request headers under cookie, but can't see it using document.cookie.
csrftoken is non httponly cookies, still i don't know why it not visible in document.cookie in client side.
You have to add CSRF_TRUSTED_ORIGINS = ["localhost:3000"] inside your settings.py to allow post requests.
I finally got the solution,
Since my backend was running on other domain not on localhost.
I had added proxy for all the requests, so that they appear to be coming from same origin.
In Angular, it ca be done like below:
proxy.conf.json
{
"/**": {
"target": "<your backend url>",
"secure": false,
"changeOrigin": true
}
}
then run using,
ng serve --proxy-config proxy.conf.json
I was looking to run my django and reactjs web application on mobile by connecting it to mac via hotspot, and changing the host to the ipaddress of the mobile. Thus, I changed my localhost to 192.168.43.19 in /etc/hosts/, and thus, my code is easily shared between mobile and mac, and I am able to run the localhost app on my mobile which is connected to mac via hotspot.
The backend is created in django rest framework. The problem is that all the get and post calls to the api created in the backend in django is being converted to options calls, and thus there are no returns, and the code is not working properly. While searching online, it said that the issue is because by default Access-cross-origin-policy is not allowed. To try handling the issue, I added the frontend url in CORS_ORIGIN_WHITELIST in the settings file of the django app, but it didnt work.
The CORS_ORIGIN_WHITELIST value set is the one, where the react code is being run. It is
CORS_ORIGIN_WHITELIST = (
'http://192.168.43.194:3000',
)
It will be really helpful, if someone could recommend me the correct way to handle this?
We are using AngularJS and Django frontend and backend respectively. We are facing CORS error as we added corsheaders in installed_app and also added middlewares still we are facing the same problem
We are using AngularJS v1.6.3, Django 1.10.11 and Python 2.7.
Angular Controller:
var socket = io.connect('http://192.168.13.129:8000/');
socket.on('connect', function (data) {
console.log('connected')
})
in django settings.py
INSTALLED_APPS = (
'corsheaders',
)
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
CORS_ORIGIN_ALLOW_ALL=True
The expected result is Socket.IO CORS request to be done successfully, but we are getting following error:
Access to XMLHttpRequest at
'http://192.168.13.129:8000/socket.io/?EIO=3&transport=polling&t=MncX14t'
from origin 'http://192.168.13.148:8082' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.
The quick and dirty solution that a lot of people go to with CORS is to disable it by allowing all origins. But this opens the doors to vulnerabilities such as CSRF attacks against your users.
In your case, what I recommend that you do is that you enable only the origin(s) from where you expect to receive requests. From your example, the correct and secure Socket.IO configuration you'd want to use is this:
sio = socketio.Server(cors_allowed_origins="http://192.168.13.148:8082")
And if you have additional origins, just make the above argument a list and add all your origins there. A * is okay for internal tests, but not a good idea for a production site unless you really know what you are doing.
I'm working on a project with Django Rest Framework as back-end and React as front-end. When I set a session variable initially in some function/view and later when I try to access the different view through axios call and in that view if I try to access session variable which i created previously, I get KeyError. Session doesn't seem stored.
I googled I got a similar issue which I'm facing.
Django rest framework Reactjs sessions not working
I followed the process by adding { withCredentials: true } in axios call. Now I'm getting a different error. Now the issue is not able to access the backend. I get an error saying Access to XMLHttpRequest at 'http://127.0.0.1:8000/url/' from origin 'http://localhost:3000' has been blocked by CORS policy
Again I googled the issue which I'm getting and found that I've to add CORS_ORIGIN_WHITELIST in the django settings.py
I followed the below post for that
Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox
I have added CORS_ORIGIN_WHITELIST like this
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
'http://127.0.0.1:3000'
]
Still, I'm facing the same issue. I don't know what's going wrong.
Finally after so much of research I found a solution for this.
In the file where we are importing axios to make the call, set the default header below your import
axios.defaults.withCredentials = true;
example:
import axios from "axios";
axios.defaults.withCredentials = true;
axios.get("url")
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
});
once this is done go to your settings.py file and add the below configuration
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
so after this if you set a session variable and access it later in any view, you would be able to get the value which you had previously stored.
This solution worked for me. Hopefully if anyone has the same issue, it will work for them too. :)
NOTE
If the session is not storing under localhost:3000 then make sure that you're accessing your front-end application through 127.0.0.1:3000. If you access the front-end application through localhost and if your backend is running on 127.0.0.1 then the session cookie will be set to 127.0.0.1, so changing the front-end URL from localhost:3000 to 127.0.0.1:3000 will solve your problem.
I had a similar issue once. I used firefox as a browser and got the problem solved by installing the CORS everywhere plugin for firefox (https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/). So, if you're using firefox, this might solve your problem.
i'm making a web app in a restful way.
For my client side i'm using angularJs, the same is hosted at - lets say -
https://domain.com
My backend is built on spring boot and i call all the resources from a subdomain - lets say -
https://xyz.domain.com
Now when a user logs in , the backend sends an http only cookie to the client.
I can see the cookie in response header but its not being set in the browsers cookie.
After a bit of research, i have tried sending cookie with domain = .domain.com
but that didnt work either.
Is there a way i can set cookie coming from xyz.domain.com for my client side at domain.com
(Note - i'm not using www.domain.com )
Any help or clue would be great.
Thank you for going through my question.
The problem you're describing is related to cross domain cookie policies. I don't know your exact use-case, but looking at CORS and P3P headers should give you a good start. As an option, you can try setting your cookie manually via Javascript.
Making CORS working isn't enough, you also need to enable withCredentials in angular.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Example:
angular.module('example', []).config(function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
});