nodejs isn't getting default cookie that django sets for users - django

I have just pushed a web app into production and requests to my nodejs no longer contain the user cookie that Django has been setting by default on my localhost (where it was working).
my nodejs looks for the cookie like this
io.configure(function(){
io.set('authorization', function(data, accept){
if (data.headers.cookie) {
data.cookie = cookie_reader.parse(data.headers.cookie);
return accept(null, true);
}
return accept('error',false);
});
io.set('log level',1);
});
and on localhost has been getting this
cookie: 'username="name:1V7yRg:n_Blpzr2HtxmlBOzCipxX9ZlJ9U"; password="root:1V7yRg:Dos81LjpauTABHrN01L1aim-EGA"; csrftoken=UwYBgHUWFIEEKleM8et1GS9FuUPEmgKF; sessionid=6qmyso9qkbxet4isdb6gg9nxmcnw4rp3' },
in the request header.
But in production, the header is the same but except no more cookie. Does Django only set this on localhost? How can I get it working in production?
I've tried setting these in my settings.py
CSRF_COOKIE_DOMAIN = '.example.com'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = False
But so far no good.
Any insight would be great.

I just figured it out. I was making a request to nodejs on the client like this
Message.socket = io.connect('http://123.456.789.10:5000');
Where I used my respective IP address and port that my nodejs was listening on. This is considered cross domain so browsers won't include cookies in the request. Easy fix by changing it to
Message.socket = io.connect('http://www.mydomain.com:5000');

Related

There is no cookie at all in my Next.Js frontend

I made Django Backend. and Next.js Frontend. There is cookie which has _ga, csrftoken when I tested on local server 127.0.0.1.
BUT, there is no cookie at all on my production (which has different domain backend and frontend).
I guessed that everything happened because I used different domain when production. Here is some django settings.py I have
ALLOWED_HOSTS = [
"127.0.0.1",
"localhost",
"BACKENDURL",
"FRONTENDURL",
"*.FRONTENDURL",
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CSRF_TRUSTED_ORIGINS = [
"http://127.0.0.1:3000",
"http://localhost:3000",
"https://*.frontendURL",
"https://FRONTENDURL",
]
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
For the future visitors...
I figured out what I was wrong.
In Development Settings,
I use same domain
[127.0.0.1:3000] as frontend (Next.JS)
[127.0.0.1:8000] as backend (Django)
But, In Production Settings,
I use different domain
[frontend.com] as frontend
[backend.com] as backend
Which leads "cross-site" error on request/response.
I also found that there is no cookie in my production
due to I use different domain in production
Different domain cannot use same cookie => No Cookie on the frontend.
Thus, I have to set the domain same on backend and frontend in 'hosting service site'
www -> frontendurl
backend -> backendurl
=> Then I can get the csrftoken and sessionid when login.
Also, I made my settings.py in django project including...
SESSION_COOKIE_DOMAIN = ".mydomain"
CSRF_COOKIE_DOMAIN = ".mydomain"
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
I recognize that CORS_ALLOW_ALL_ORIGINS leads some danger...
I set it just to confirm that everything is fine.
Later on, In production, change it into
CORS_ALLOWED_ORIGINS = [...]
Hope my answer helped someone.
Happy Hacking my friends. Good Luck!

flask sessions not persistent between requests from cross domains

I have a frontend vue site hosted on google's firebase with the url (https://front-end.web.com) , while my flask backend is hosted on heroku with the url (https://back-end.heroku.com). This makes my session not to persist across requests, I tried fixing this by implementing CORS on my backend, but for some reason it's not working , below are snippets of my code to show my implementation
config_class.py
class ConfigClass():
CORS_ALLOW_HEADERS = ['Content-Type']
CORS_ORIGINS = ['https://front-end.web.com']
SECRET_KEY = os.environ.get("APP_SECRET_KEY")
SESSION_TYPE = 'redis'
_init.py
from flask import Flask, session
from flask_session import Session
from flask_cors import CORS
from root_folder.config import ConfigClass
db = SQLAlchemy()
migrate = Migrate()
ma = Marshmallow()
sess = Session()
def create_app(ConfigClass):
# initiate the flask app and assign the configurations #
app = Flask(__name__)
app.config.from_object(config_options[config_class])
sess.init_app(app)
from root_folder.clients import clients_app
# register all the blueprints in this application
app.register_blueprint(clients_app)
CORS(app, supports_credentials=True)
# return the app object to be executed
return app
app.py
from root_folder import create_app
app = create_app()
Procfile:
web: gunicorn -w 1 app:app
axios front end request
let formData = new FormData();
formData.append("email", email);
formData.append("password", password);
axios.post(
backendUrl+'create_client_account',
formData,
{
withCredentials: true,
headers:{
"Content-Type": "multipart/form-data"
}
}
);
create client route ( I have stripped this code block to the bare minimum to make it understandable):
from flask import session
# route for creating account credentials
#bp_auth_clients_app.route("/create_client", methods=["POST"])
def create_client():
username = request.form.get("username").lower()
email = request.form.get("email").lower()
# create account code goes here #
auth_authentication = True
session["auth_authentication"] = auth_authentication
req_feedback = {
"status": True,
"message": "Account was successfully created",
"data": feedback_data
}
return jsonify(req_feedback), 200
After the account is successfully created, I am unable to access the session value in subsequent requests, it returns None.
To recreate the problem on my local server, I access the front-end via the domain "localhost:8080" , while I access the flask server via "127.0.0.1:8000" . If I change the front end domain to "127.0.0.1:8080", I don't usually have any problems.
Kindly advice on what to do.
Thanks to Ahmad's suggestion, I was able to resolve the issue using custom domains for both my frontend and backend as follows:
frontend.herokuapp.com -> customDomain.com
backend.herokuapp.com -> api.customDOmain.com
finally I added the line below to my session config:
SESSION_COOKIE_DOMAIN = ".customDomain.com"
And all was well and good.
Sessions use cookies:
On session creation the server will send the cookie value in the set-cookie header. It doesn't work for you because of cross origin issue.
It works fine for you when you use 127.0.0.1 because 127.0.0.1:8080 and 127.0.0.1:8000 are the same origin so the browser accepts the set-cookie header and do set the cookie no problem.
Cookies are sent in the header on each request and your server loads the session from Redis by cookie value (The cookie value is called session_id).
How it gets inserted => Normally your session gets serialized and inserted in Redis with the cookie hash as Key in the end of the request life cycle.
If you want to keep using sessions and cookies you need to find another solution for your deployment to so that your backend and frontend have the same hostname.
If you can't do I'd recommend to read about JWT (Json-Web-Tokens).
EDIT
You can send the session id in your response body and save it in local storage.
Then you need to configure:
frontend set the session id value it in the Authorization header base64 encoded.
Backend base64 decode Authorization header value from request and check for the session in Redis, if exists load it.
EDIT
How to deploy both backend/frontend on same hostname using apache:
using apache you need to create 2 virtual hosts one for backend and the other for frontend listening on different ports then configure your web server deployment to use the backend VH if the path is prefixed by /api/ and use the frontend Virtual host for anything else.
This way any request you make to your api your backend will handle it otherwise it'll serve your frontend app.
This is just a way on how to do it there is plenty others
Check this question.

Login not working in django when using rewrites from firebase hosting to cloud run

Current Setup: I've got a Django application behind gunicorn running on Cloud Run. Since the region it is deployed in does not support Custom Domains, I have a firebase hosting setup with the following code:
{
"hosting": {
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [{
"source": "/**",
"run": {
"serviceId": "website",
"region": "ap-south1"
}
}]
}
}
The relevant settings in settings.py:
CSRF_TRUSTED_ORIGINS = ['.<domain>.com']
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
The problem: However, the login form on /admin does not work if I access the site using my domain name https://doman.com/admin even though it works fine if I use the Cloud Run endpoint https://endpoint-uw.a.run.app.
Faulty behaviour: When accessing it from my domain, the login page shows up, I enter my credentials and log in, it adds the relevant cookies to my browser but then it redirects me back to the login page.
Could it be that since the URL is being rewritten by firebase django is expecting a cookie from uw.a.run.app? I tried adding the setting SESSION_COOKIE_DOMAIN = '.<domain>.com' but that did not fix it either, it just made the Cloud Run endpoint stop working as well.
Any advice on how to fix this or how to diagnose what is going wrong would be much appreciated, thanks!
The relevant settings in settings.py:
SESSION_COOKIE_NAME = "__session"
as firebase send cookie in the name "__session"

Why my angular HTTP request can't GET on local Django server?

I made an Angular application able use an online api to get a json and do stuff.
But, although the json is the same, if I try to change only the url of the json by setting a local url of a server written in django, angular would seem not to connect anymore ...
My question is, why if with an online cloud server works, with a local one wouldn't?
I tried making this server "on cloud" opening the router's port, also setting up a ddns, and using postman or a browser it seems to work, but when i try to connect with angular it still doesn't get the data...
I am sure 100% that the server answer, with the right json data, because django prints on console that he received a HTTP GET request :
http://i.imgur.com/TIQnIcR.png
I remind you that the HTTP angular request worked with another api, but i will still show up some code :
export class ProdottoService {
private prodotti: Array<ProdottoModel>;
constructor(private httpClient: HttpClient) {
this.prodotti = new Array<ProdottoModel>();
var url:string = "https://gist.githubusercontent.com/saniyusuf/406b843afdfb9c6a86e25753fe2761f4/raw/523c324c7fcc36efab8224f9ebb7556c09b69a14/Film.JSON";
var local_url:string = "http://127.0.0.1:8000/films/?format=json";
httpClient.get(local_url)
.subscribe((films : Array<Object> ) => {
films.forEach((film => {
this.prodotti.push(new ProdottoModel(film));
}));
}
);
}
getProdotti(): Array<ProdottoModel> {
return this.prodotti;
}
}
Result using external api :
http://i.imgur.com/MT7xD9c.png
Thanks in advace for any help :3
-- EDIT -- IS A CORS ISSUE
In django settings.py file :
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:4200'
)
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
But i don't know if there's a way to set-up CORS settings in Angular
Based on feedback, this is a CORS issue. Your Django server is getting the requests and responding because localhost is an implicitly trusted domain in Django's dev environment, but it isn't configured properly to set the cross origin header, so the browser is not allowing your app to see the response because the server hasn't authorized the domain explicitly.
The problem here is that you've set CORS white list like this:
CORS_ORIGIN_WHITELIST = ( 'localhost:8000', '127.0.0.1:4200' )
it needs to be like this:
CORS_ORIGIN_WHITELIST = ( 'localhost:4200' )
angular runs on localhost, not 127.0.0.1, even though that's what localhost is an alias for, your browser still differentiates them for CORS. Also, you do not need to whitelist the domain your serving off of, that's not crossing any origin as it's the same origin.
In your screenshot, it looks like the response is type "document..." something. The simplest fix, with only the code here, is to convert the string to JSON.
JSON.parse(films)
This is the wrong answer, because it's being set to that because of the CORS issue in the other answers.

How to make game use https when played via facebook and http when played from other domain

Our users play our Django game directly via our domain, cnamed to herokuapp.com. We request our assets via http.
We want to add our game to facebook, which requires using https. Heroku can handle this.
Using https requests: our game works on facebook but fails to load assets when accessed via our cnamed domain.
Can we make our game use https when played via facebook and http when played from our domain? What code must we add to settings.py?
We've tried this code in settings.py but it didn't work
Option 1:
import socket
if socket.gethostname().startswith('app'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
Option 2:
import socket
if socket.gethostname().startswith('edge'):
LIVEHOST = True
else:
LIVEHOST = False
if LIVEHOST:
STATIC_URL = "https://d******1.cloudfront.net/"
else:
STATIC_URL = "http://d******1.cloudfront.net/"
You could use protocol relative urls to save yourself from the pain of worrying about the protocol to use.
So the settings would look like:
STATIC_URL = "//d******1.cloudfront.net/"
and you can safely get rid of all the computation logic in your code snippet.