限制登录用户访问静态文件 [英] Restrict static file access to logged in users

查看:27
本文介绍了限制登录用户访问静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制文件对登录用户可用,否则返回 403 错误或类似错误.例如,用户只有在登录后才能查看/下载 /static/data/example.csv.

I want to restrict files to be available to logged in users, but otherwise return a 403 error or similar. For example a user should be able to view/download /static/data/example.csv only if they're logged in.

如果他们没有登录,我知道如何使用 Flask-Login 控制文件的实际显示,但不知道如果他们直接在浏览器中访问链接,如何阻止对文件的访问.

I know how to control the actual displaying of the files using Flask-Login if they're not logged in, but not how to block access to the file if they visit the link directly in their browser.

推荐答案

Flask 添加静态路由来提供静态文件.在生产中,您通常会短路".这条路线,以便 Nginx 在请求到达您的应用程序之前提供文件.与其添加此短路",不如将其删除并让 Flask 处理请求.用 Flask-Login 的 login_required 包裹的路由覆盖静态路由.

Flask adds a static route to serve static files. When you're in production, you typically "short circuit" this route so that Nginx serves the files before the request ever gets to your app. Instead of adding this "short circuit", leave it out and let Flask handle the requests. Overwrite the static route with one that is wrapped by Flask-Login's login_required.

from flask_login import login_required

app.view_functions['static'] = login_required(app.send_static_file)

不过,这通常是矫枉过正,因为无论如何您都希望提供真正的静态文件,这样页面对于未登录的用户来说看起来是正确的(否则 CSS 甚至不会被发送到登录页面).取而代之的是短路".由 Nginx 提供的静态文件夹,并定义一个路由,该路由将从其他目录(例如实例文件夹)提供受保护的文件.请参阅flask.send_from_directory.

This is typically overkill though, since you want truly static files to be served no matter what so that pages look right to non-logged in users (otherwise the CSS wouldn't even be sent for the login page). Instead, "short circuit" the static folder to be served by Nginx, and define a route that will serve protected files from some other directory, such as the instance folder. See flask.send_from_directory.

import os
from flask import send_from_directory
from flask_login import login_required

@app.route('/protected/<path:filename>')
@login_required
def protected(filename):
    return send_from_directory(
        os.path.join(app.instance_path, 'protected'),
        filename
    )

这将提供来自protected"目录的文件.在 instance 文件夹 中,仅供登录用户使用.还可以添加其他限制,例如只允许某些用户访问某些文件.与静态路径类似,您可以使用以下命令生成文件的 url:

This will serve files from the directory "protected" in the instance folder to logged in users only. Other restrictions could also be added, such as only allowing certain users access to certain files. Similar to the static path, you can generate a url to a file with:

url_for('protected', filename='data/example.csv')

这篇关于限制登录用户访问静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆