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.
If you add javascript, with a bit of pre-processing it is possible to securely password protect a page, no server-side validation needed. Encrypt your content with a symmetric key algo like AES (that's the pre-processing), put it online and use javascript to decrypt that content with a user provided password.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With