密码保护Flask应用程序中的一个网页 [英] Password Protect one webpage in Flask app

查看:177
本文介绍了密码保护Flask应用程序中的一个网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个Flask web应用程序,并使用Apache基本身份验证(使用.htaccess和.htpasswd文件)来密码保护它。我想密码只保护应用程序中的一个网页。当我的密码保护网页的HTML文件没有效果,网页仍然没有密码保护。这可能是因为它是我的Python文件使用render_template调用HTML文件?我不知道如何解决这个问题。

解决方案

您需要限制对端点的访问。 这个片段应该让你开始正确的道路。


$从functools进口包装



def check_auth(username,password)$:
$ p $

返回用户名=='admin'和密码=='secret'
$ b $ def authenticate():
发送401响应,启用基本身份验证
返回响应(
'无法验证您的访问级别那个URL.\\\
'
'你必须用适当的凭证登录',401,
{'WWW-Authenticate':'Basic realm =需要登录})

def require_auth(f):
@wraps(f)
def装饰(* args,** kwargs):
auth = request.authorization
如果不是auth或者不是check_auth(auth.username,auth.password):
返回authenticate()
返回f(* args,** kwargs)
返回装饰

有了这个,你可以用 @requires_auth 来装饰你想要限制的任何端点。

  @ app.route('/ secret-page')
@requires_auth
def secret_page():
return render_template('secret_page.html')


I am running a Flask web app and using Apache basic authentication(with .htaccess and .htpasswd files) to password protect it. I want to password protect only one webpage in the app. When I password protect the html file for the webpage there is no effect and the webpage is still not password protected. Could this be because it is my python file that is calling the html file using render_template? I'm not sure how to fix this issue.

解决方案

You need to restrict access to your endpoint. This snippet should get you started down the right path.

from functools import wraps
from flask import request, Response


def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'admin' and password == 'secret'

def authenticate():
    """Sends a 401 response that enables basic auth"""
    return Response(
    'Could not verify your access level for that URL.\n'
    'You have to login with proper credentials', 401,
    {'WWW-Authenticate': 'Basic realm="Login Required"'})

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

With this, you could decorate any endpoint you want to restrict with @requires_auth.

@app.route('/secret-page')
@requires_auth
def secret_page():
    return render_template('secret_page.html')

这篇关于密码保护Flask应用程序中的一个网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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