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

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

问题描述

我想限制文件可以登录用户,但否则返回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 wouldn'甚至不会被发送到登录页面)。相反,将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目录中的文件仅限登录用户。还可以添加其他限制,例如只允许某些用户访问某些文件。类似于静态路径,您可以使用以下命令生成一个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天全站免登陆