python - 如何获得与 Flask 一起使用的 is_safe_url() 函数以及它是如何工作的?

标签 python security flask

Flask-Login 建议在用户登录后使用 is_safe_url() 函数:

这是讨论此问题的文档部分的链接:
https://flask-login.readthedocs.io/en/latest/#login-example

他们链接到这个片段,但我不明白它是如何实现的 is_safe_url() :
https://palletsprojects.com/p/flask/

next = request.args.get('next')
if not is_safe_url(next):
     return abort(400)

这似乎不是 Flask 自带的。我对编码比较陌生。我想明白:
  • request 时究竟发生了什么获取 next争论?
  • is_safe_url()有什么用功能做什么来确保 URL 是安全的?
  • 是否只需要在登录时检查下一个 URL?或者是否有其他地方和时间包含此安全措施很重要?
  • 最重要的是:是否有可靠的 is_safe_url()我可以与 Flask 一起使用的功能?

  • 编辑:添加了 Flask-Login 文档的链接并包含了代码片段。

    最佳答案

    正如评论中提到的,今天(2020 年 4 月 26 日)的 Flask-Login 在文档(GitHub 上的 issue)中有死链接。请注意原始 flask 片段文档中的警告:

    Snippets are unofficial and unmaintained. No Flask maintainer has curated or checked the snippets for security, correctness, or design.


    片段是
    from urllib.parse import urlparse, urljoin
    
    def is_safe_url(target):
        ref_url = urlparse(request.host_url)
        test_url = urlparse(urljoin(request.host_url, target))
        return test_url.scheme in ('http', 'https') and \
               ref_url.netloc == test_url.netloc
    
    现在回答您的问题:

    What exactly is happening when request gets the next argument?


    我们在这里关注的部分代码是
    next = request.args.get('next')
    return redirect(next or url_for('dashboard')) 
    
    默认情况下将用户重定向到仪表板(例如成功登录后)。但是,如果用户试图达到例如端点 profile并且没有登录,我们希望将他重定向到登录页面。登录后默认重定向会将用户重定向到 dashboard而不是 profile他打算去的地方。为了提供更好的用户体验,我们可以通过 building URL 将用户重定向到他的个人资料页面/login?next=profile ,这使 flask 能够重定向到 profile而不是默认 dashboard .
    由于用户可以滥用 URL,我们希望检查 URL 是否安全,否则中止。

    What does the is_safe_url() function do to ensure the URL is safe?


    有问题的代码段是一个函数,可确保重定向目标将指向同一服务器。

    Does the next URL need to be checked on login only? Or are there other places and times when it is important to include this security measure?


    不,您应该检查所有危险的 URL。安全 URL 重定向的示例是 redirect(url_for('index')) ,因为它在您的程序中进行了硬编码。请参阅 Unvalidated Redirects and Forwards - OWASP cheatsheet 上的安全和危险 URL 示例.

    And most importantly: is there a reliable is_safe_url() function that I can use with Flask?


    pypi 上捆绑了 Django 的 is_safe_url() 作为独立包。 .

    关于python - 如何获得与 Flask 一起使用的 is_safe_url() 函数以及它是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60532973/

    相关文章:

    python - keras 中用于评估符号预测的自定义指标

    python - process.communicate 和 getche() 失败

    python - 在 postgresql 的引号或其他需要引号的代码行中列出?

    php - 安全登录 : public key encryption in PHP and Javascript

    CSS 中的 Python 变量

    Python:如何从数据帧中行查找数据并根据列匹配在另一个数据帧中相乘

    security - 安全图像有什么好处,比如银行网站登录?

    java - 具有客户端模板的受限页面

    python - Flask 后台网页抓取和数据库更新

    python - 通过 Flask 运行时 CSS 无法正常工作