Password Protect one web page in Flask app

I am running a Flask web app and using Apache Basic Authentication (with .htaccess and .htpasswd files) to secure it. I want the password to protect only one web page in the application. When I protect the password of the html file for the webpage, the effect has no effect and the webpage is still not password protected. Could it be because it is my python file that is calling the html file using render_template? I am not sure how to solve this problem.

+3


source to share


1 answer


You need to restrict access to your endpoint. This snippet should start working on the right track.

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 can decorate any endpoint you want to constrain with @requires_auth

.

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

      

+10


source







All Articles