authomatic icon indicating copy to clipboard operation
authomatic copied to clipboard

Limit domain for google login, so it doesn't conflict with a subdomain?

Open BobStein opened this issue 4 years ago • 1 comments

I have a pair of sites that both use authomatic with Flask-login for google OAuth2,

https://unslumping.org/ https://fun.unslumping.org/

Each works fine if I clear all cookies in both domains before I log in. But logging in to the 2nd level domain seems to mess up logging in to the 3rd level domain. I get caught in a loop where .login() keeps returning an object with a .error either "Unable to retrieve stored state!" or "The returned state csrf cookie ... doesn't match with the stored state!"

Is there a way I can limit the scope of cookies to the root domain, and not let them be used by the subdomain?

BobStein avatar Aug 16 '21 22:08 BobStein

Hi - thanks for raising this issue.

I've just been having a look at the spec for setting cookies, which seems to be in RFC2109. It looks like the default position is that cookies are shared, unless the Set-Cookie header has Domain set (which is not the default in authomatic). However if you set it to e.g. example.com then it is valid for all subdomains as well, so the only wayDomain can be useful is if you have 2 'sibling sites' to separate, e.g. www.example.com and foo.example.com

Apparently one way round this is to use the Content Security Policy sandbox option, by setting the following header on all requests https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/sandbox

So you likely want to set a header such as:

Content-Security-Policy: sandbox allow-forms allow-scripts;

This should prevent the sharing of cookies between pages, and thus prevent this problem.

I've not tried this on Flask, but their docs suggest that you should be able to set a header on every response by doing:

@app.after_request
def apply_csp(response):
    response.headers["Content-Security-Policy"] = "sandbox allow-forms allow-scripts;"
    return response

Please let us know if this fixes your problem!

mrichar1 avatar Aug 17 '21 09:08 mrichar1