OAuthlib thinks request is insecure because of reverse proxy

I have noticed that for every request, request.scheme is http. I can't find any official source why, but I have been told by my peers this is because of Cloudflare acting as reverse proxy and a tls terminator, causing my server's hosting provider to see http instead of https.

One part of my app uses the Google Classroom API, and I have configured a callback to a secure endpoint of my server. Upon attempting to fetch a token from the callback's absolute uri, oauthlib raises oauthlib.oauth2.rfc6749.errors.InsecureTransportError: (insecure_transport) OAuth 2 MUST utilize https. because it thinks the request is http and insecure. I have researched and found out I can set os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' to mitigate this issue, but I am hesitant to do so because I am unsure if that compromises security.

My thought process is to manually change the request url to https when I'm absolutely sure it is secure. Inspecting request.META to find which headers are set in the case of a reverse proxied http request, the code looks like this:

authorization_response = request.build_absolute_uri()
if (
    authorization_response.startswith("http://") and
    request.META["HTTP_X_FORWARDED_PROTO"] == "https" and
    request.META["HTTP_ORIGIN"].startswith("https") and
    json.loads(request.META["HTTP_CF_VISITOR"])['scheme'] == "https"
):
    authorization_response = "https://" + authorization_response[7:]

... fetch the token passing authorization_response and etc

which seems to work.

Considering how little information I could find this online, I was wondering if this is a best practice and if there's a better way of letting oauthlib know the request is secure. Or, since my domain has HSTS preload, is this all unnecessary and I can get away with setting os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'?

Back to Top