How to prevent the Open Redirect vulnerability with the next parameter in Flask

Let’s say someone codes a url like this:

Now an attacker can craft the url like that:

If you don’t sanitise the next, your user will be taken to the evil site. This is the Open Redirect vulnerability.

That’s why you must make sure urls are safe. You do it like that:

from flask import request, g, redirect
from urllib.parse import urlparse, urljoin

def is_safe_redirect_url(target):
    host_url = urlparse(request.host_url)
    redirect_url = urlparse(urljoin(request.host_url, target))
    return (
        redirect_url.scheme in ("http", "https")
        and host_url.netloc == redirect_url.netloc

def get_safe_redirect(url):

    if url and is_safe_redirect_url(url):
        return url

    url = request.referrer
    if url and is_safe_redirect_url(url):
        return url

    return "/"

Just pass your url to get_safe_redirect.

The above is a courtesy of the from the Shopyo project.

5 thoughts on “How to prevent the Open Redirect vulnerability with the next parameter in Flask”

  1. hello there and thank you for your information – I have definitely picked up anything new from right here. I did however expertise a few technical points using this web site, since I experienced to reload the web site many times previous to I could get it to load correctly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high quality score if advertising and marketing with Adwords. Well I’m adding this RSS to my email and could look out for a lot more of your respective intriguing content. Make sure you update this again soon.|

  2. I simply could not leave your website prior to suggesting that I really loved the usual information a person supply for your visitors? Is gonna be again often in order to investigate cross-check new posts|

  3. If you are going for finest contents like I do, simply go to see this site everyday as it presents feature contents, thanks|

  4. Wow, awesome blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is magnificent, let alone the content!|

  5. Thank you a bunch for sharing this with all of us you actually know what you are speaking about! Bookmarked. Kindly additionally seek advice from my site =). We could have a hyperlink exchange arrangement between us|

Leave a Comment

Your email address will not be published. Required fields are marked *