| 1 |
#!/usr/bin/env python |
| 2 |
"""Multiple authentication example |
| 3 |
|
| 4 |
This example demonstrates how to combine two authentication methods using the |
| 5 |
"MultiAuth" class. |
| 6 |
|
| 7 |
The root URL for this application can be accessed via basic auth, providing |
| 8 |
username and password, or via token auth, providing a bearer JWS token. |
| 9 |
|
| 10 |
This example requires the PyJWT package to be installed. |
| 11 |
""" |
| 12 |
from time import time |
| 13 |
from flask import Flask |
| 14 |
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth |
| 15 |
from werkzeug.security import generate_password_hash, check_password_hash |
| 16 |
import jwt |
| 17 |
|
| 18 |
|
| 19 |
app = Flask(__name__) |
| 20 |
app.config['SECRET_KEY'] = 'top secret!' |
| 21 |
|
| 22 |
basic_auth = HTTPBasicAuth() |
| 23 |
token_auth = HTTPTokenAuth('Bearer') |
| 24 |
multi_auth = MultiAuth(basic_auth, token_auth) |
| 25 |
|
| 26 |
|
| 27 |
users = { |
| 28 |
"john": generate_password_hash("hello"), |
| 29 |
"susan": generate_password_hash("bye") |
| 30 |
} |
| 31 |
|
| 32 |
for user in users.keys(): |
| 33 |
token = jwt.encode({'username': user, 'exp': int(time()) + 3600}, |
| 34 |
app.config['SECRET_KEY'], algorithm='HS256') |
| 35 |
print('*** token for {}: {}\n'.format(user, token)) |
| 36 |
|
| 37 |
|
| 38 |
@basic_auth.verify_password |
| 39 |
def verify_password(username, password): |
| 40 |
if username in users: |
| 41 |
if check_password_hash(users.get(username), password): |
| 42 |
return username |
| 43 |
|
| 44 |
|
| 45 |
@token_auth.verify_token |
| 46 |
def verify_token(token): |
| 47 |
try: |
| 48 |
data = jwt.decode(token, app.config['SECRET_KEY'], |
| 49 |
algorithms=['HS256']) |
| 50 |
except: # noqa: E722 |
| 51 |
return False |
| 52 |
if 'username' in data: |
| 53 |
return data['username'] |
| 54 |
|
| 55 |
|
| 56 |
@app.route('/') |
| 57 |
@multi_auth.login_required |
| 58 |
def index(): |
| 59 |
return "Hello, %s!" % multi_auth.current_user() |
| 60 |
|
| 61 |
|
| 62 |
if __name__ == '__main__': |
| 63 |
app.run() |