David Yuan
David Yuan

Reputation: 820

python flask redirect to https from http

I have a website build using python3.4 and flask...I have generated my own self-signed certificate and I am currently testing my website through localhost.

I am using the python ssl module along with this flask extension: https://github.com/kennethreitz/flask-sslify

context = ('my-cert.pem', 'my-key.pem')
app = Flask(__name__)
sslify = SSLify(app)

...

if __name__ == '__main__':
    app.debug = False
    app.run(
    host="127.0.0.1",
    port=int("5000"),
    ssl_context=context
)

This does not seem to be working however. I took a look in the sslify source code and this line does not seem to be working

def init_app(self, app):
    """Configures the configured Flask app to enforce SSL."""
    app.before_request(self.redirect_to_ssl)
    app.after_request(self.set_hsts_header)

Specifically the function call to redirect_to_ssl (I added my own print statement under the redirect_to_ssl function and my statement was never printed)

def redirect_to_ssl(self):
    print("THIS IS WORKING")
    """Redirect incoming requests to HTTPS."""
    Should we redirect?
    criteria = [
        request.is_secure,
        current_app.debug,
        request.headers.get('X-Forwarded-Proto', 'http') == 'https'
    ]

    if not any(criteria) and not self.skip:
        if request.url.startswith('http://'):
            url = request.url.replace('http://', 'https://', 1)
            code = 302
            if self.permanent:
                code = 301
            r = redirect(url, code=code)
            return r

I am pretty new to python. Any ideas?

Upvotes: 46

Views: 74861

Answers (18)

Exitare
Exitare

Reputation: 582

My issue was simply that instead of using url_for, I used href="/". Once I started using url_for everything started working. Just stating in case anyone else did this.

Upvotes: 0

Edala Naveen
Edala Naveen

Reputation: 1

My Flask app was sitting on an AWS EC2, behind an ELB, inside a VPC, and on a non-standard port (8000) without a redirect at 80 to 443, so it kept missing the Access Control Headers, and also setting the response location to http, with 301 permanent redirects. A combination of @Altair7852's solution and some manual addition of response headers did the trick:

@app.after_request
def after_request(response):
    if response.location and app.env != "development":
        response.location = response.location.replace("http://", "https://", 1)
    response.headers.add('Access-Control-Allow-Origin', '{mysiteurl}')
    return response

Of course, if security is not that particular of an issue it is also reasonable to set allow origin header to '*' for no hassle. I did try to use @Nick K9's suggestion with werkzeug, but I can't get it working correctly, probably again because of the setup I'm in.

Still, it's a quick bandaid fix to just use the after request modifier function.

Upvotes: 0

Xajuan Smith
Xajuan Smith

Reputation: 1

When you expose the ports the flask in the logs shows what port it is running on?

it cannot serve http and https without their being a listener on both ports.

just run a container that redirects to the the https url serving on port 80 or 8080 depending on access. This is what brought me to this page to see if anyone else wanted to fix such a flask issue.

Upvotes: 0

Fighter178
Fighter178

Reputation: 413

Use:

app.run(port="443")

All modern browsers automatically use HTTPS when the port is 443 or 8443.

Upvotes: 1

Altair7852
Altair7852

Reputation: 1418

In my case Flask app is sitting behind AWS API Gateway and solutions with @app.before_request were giving me permanent redirects.

The following simple solution finally worked:

@app.after_request
def adjust_response(response):
    ....
    if response.location:
        if app.env != "development":
            response.location = response.location.replace("http://", "https://", 1)
    return response

Upvotes: 0

mdubez
mdubez

Reputation: 3134

On app engine flex, add:

from werkzeug.middleware.proxy_fix import ProxyFix

def create_app(config=None):

    app = Flask(__name__)
    app.wsgi_app = ProxyFix(app.wsgi_app)

In addition to the solution of:

@app.before_request
def before_request():
    if not request.is_secure:
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)

Otherwise it'll cause infinite redirects since SSL is unwrapped behind the proxy but is noted in the headers.

Upvotes: 2

Sanna Keller-Heikkila
Sanna Keller-Heikkila

Reputation: 2594

To me, it appears you're making it more complicated than it needs to be. Here is the code I use in my views.py script to force user to HTTPS connections:

@app.before_request
def before_request():
    if not request.is_secure:
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)

Upvotes: 59

I had the same issue and mine is a brute-force solution, but it works. Heroku in the past suggested flask_sslify, which is not maintained anymore. Nowadays the proper way in Flask should be flask-talisman, but I tried it and it has bad interactions with boostrap templates. I tried the anulaibar solution but it did not always worked for me. The following is what I came up with:

@app.before_request
def before_request():
    # If the request is sicure it should already be https, so no need to redirect
    if not request.is_secure:
        currentUrl = request.url
        if currentUrl.startswith('http://'):
            # http://example.com -> https://example.com
            # http://www.example.com -> https://www.example.com
            redirectUrl = currentUrl.replace('http://', 'https://', 1)
        elif currentUrl.startswith('www'):
            # Here we redirect the case in which the user access the site without typing any http or https
            # www.example.com -> https://www.example.com
            redirectUrl = currentUrl.replace('www', 'https://www', 1)
        else:
            # I do not now when this may happen, just for safety
            redirectUrl = 'https://www.example.com'
        code = 301
        return redirect(redirectUrl, code=code)

I have the domain registered in godaddy which is also redirecting to https://www.example.com.

Upvotes: 0

anulaibar
anulaibar

Reputation: 310

Thanks to answer from Kelly Keller-Heikkila and comment by jaysqrd I ended up doing this in my Flask app:

from flask import request, redirect
...

@app.before_request
def before_request():
    if app.env == "development":
        return
    if request.is_secure:
        return

    url = request.url.replace("http://", "https://", 1)
    code = 301
    return redirect(url, code=code)

I tried the flask_sslify solution suggested by Rodolfo Alvarez but ran into this issue and went with the above solution instead.

If the app is running in development mode or the request is already on https there's no need to redirect.

Upvotes: 15

Tim Ludwinski
Tim Ludwinski

Reputation: 2863

For some reason it seems, requests from a Private AWS API Gateway with a VPC endpoint don't include the "X-Forwarded-Proto" header. This can break some of the other solutions (either it doesn't work or it continuously redirects to the same url). The following middleware forces https on most flask generated internal redirects:

class ForceHttpsRedirects:
    def __init__(self, app):
        self.app = app
    
    def __call__(self, environ, start_response):
        environ["wsgi.url_scheme"] = "https"
        return self.app(environ, start_response)

# Usage
app = flask.Flask(__name__)
app.wsgi_app = ForceHttpsRedirects(app.wsgi_app) # Add middleware to force all redirects to https

Upvotes: 1

Maximilian Burszley
Maximilian Burszley

Reputation: 19634

An alternative to the other answers that I've been able to use with great success:

from http import HTTPStatus
from typing import Optional

from flask import Response, redirect, request, url_for


def https_redirect() -> Optional[Response]:
    if request.scheme == 'http':
        return redirect(url_for(request.endpoint,
                                _scheme='https',
                                _external=True),
                        HTTPStatus.PERMANENT_REDIRECT)


# ..

if app.env == 'production':
    app.before_request(https_redirect)

# ..

Upvotes: 3

Evan G
Evan G

Reputation: 11

I ran into the same solution running a Flask application in AWS Elastic Beanstalk behind a load balancer. The following AWS docs provided two steps to configure the environment for http redirects: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/configuring-https-httpredirect.html Following both steps fixed my issue.

One thing to note is that you'll have to create the .ebextenions folder at the root level of your application source bundle and add the config file to that .ebextensions folder. The readme here: https://github.com/awsdocs/elastic-beanstalk-samples explains this in a bit more detail.

Upvotes: 1

JayS
JayS

Reputation: 2283

Here is a flask solution if you are on aws and behind a load balancer. Place it in your views.py

@app.before_request
def before_request():
    scheme = request.headers.get('X-Forwarded-Proto')
    if scheme and scheme == 'http' and request.url.startswith('http://'):
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)

Upvotes: 11

Wietze
Wietze

Reputation: 51

I use a simple extra app that runs on port 80 and redirect people to https:

from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("https://example.com", code=302)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)

Upvotes: 5

Eyal Levin
Eyal Levin

Reputation: 18376

The Flask Security Guide recommends using Flask-Talisman.

$ pip install flask-talisman

Usage example:

from flask import Flask
from flask_talisman import Talisman

app = Flask(__name__)
Talisman(app)

It forces HTTPS by default (from the README):

force_https, default True, forces all non-debug connects to https.


Personally, I got some errors relating to CSP (Content Security Policy) which I disabled with:

Talisman(app, content_security_policy=None)

But use this at your own risk :)

Upvotes: 19

MohanBabu
MohanBabu

Reputation: 475

I'm using cloud foundry python app which is behind a load balancer (like https://stackoverflow.com/users/5270172/kelly-keller-heikkila said) . This resolution helped me by adding (_external and _Scheme to the url_for function). https://github.com/pallets/flask/issues/773

Upvotes: 0

Rodolfo Alvarez
Rodolfo Alvarez

Reputation: 990

According with the docs, after pip install Flask-SSLify you only need to insert the following code:

from flask import Flask
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

I have done it and it works very well. Am I missing something in the discussion ?

Upvotes: 19

tuned
tuned

Reputation: 1125

The standard solution is to wrap the request with an enforce_ssl decorator that after checking some flags in the app configuration (flags you can set depending on your debugging needs) modifies the request's url with request.url.

As it is written here.

You can modify the code to make it working with before_request as suggested by @kelly-keller-heikkila

Upvotes: 5

Related Questions