It's very easy to do with the Flask extension Flask-HTTPAuth.
Installation
$ pip install flask-httpauth
from flask_httpauth import HTTPBasicAuth
instance with ʻauth = HTTPBasicAuth ()
@ auth.get_password
@ auth.login_required
app.py
from flask import Flask
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {
"john": "hello",
"susan": "bye"
}
@auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % auth.username()
if __name__ == '__main__':
app.run()
MD5 hash the username and password before sending them to the server. Measures against eavesdropping and tampering that could not be prevented by Basic authentication.
Just change HTTPBasicAuth
to HTTPDigestAuth
.
app.py
from flask import Flask
from flask_httpauth import HTTPDigestAuth
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret key here'
auth = HTTPDigestAuth()
users = {
"john": "hello",
"susan": "bye"
}
@auth.get_password
def get_pw(username):
if username in users:
return users.get(username)
return None
@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % auth.username()
if __name__ == '__main__':
app.run()
ToDo: Find out about
pathlib
, ʻits dangerous`
Recommended Posts