How to set up a single-jar application to handle multiple domains?

Currently, my flash application (which uses sessions) performs the following operations for ONE domain:

app.config.from_object (Settings)

and in the settings object:

SESSION_COOKIE_DOMAIN = ".first.com"

Now I would like to dynamically set the session cookie domain to process, for example, requests from www.first.com and www.second.com. Please note that I am talking about domains, but not about subdomains. Thanks.

+5
source share
1 answer

Grepping SESSION_COOKIE_DOMAIN via the Flask Github repo shows that it is used like this :

 def get_cookie_domain(self, app): """Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used. """ if app.config['SESSION_COOKIE_DOMAIN'] is not None: return app.config['SESSION_COOKIE_DOMAIN'] if app.config['SERVER_NAME'] is not None: # chop of the port which is usually not supported by browsers rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] # Google chrome does not like cookies set to .localhost, so # we just go with no domain then. Flask documents anyways that # cross domain cookies need a fully qualified domain name if rv == '.localhost': rv = None # If we infer the cookie domain from the server name we need # to check if we are in a subpath. In that case we can't # set a cross domain cookie. if rv is not None: path = self.get_cookie_path(app) if path != '/': rv = rv.lstrip('.') return rv 

By doing the same with get_cookie_domain( , you see :

 def save_session(self, app, session, response): domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) ... 

OK Now we only need to figure out which domain name to use. Digging out docs or code , you will see that save_session() is called in the context of the request. Therefore, you just need to import the request object from the flask module:

 from flask import request 

and use it inside save_session() to determine the domain name for cookies (for example, from the Host header), for example:

 def save_session(self, app, session, response): domain = '.' + request.headers['Host'] path = self.get_cookie_path(app) # the rest of the method is intact 

The only time you need to specify a cookie domain is when you send it back with the response object.

Also note that the Host header may be missing.

To link all this, you need to specify your version (subclass) of SecureCookieSessionInterface :

 app = Flask(__name__) app.session_interface = MySessionInterface() 

Additional doc links:

+6
source

Source: https://habr.com/ru/post/1206177/


All Articles