| 1 |
#!/usr/bin/env python |
| 2 |
"""Token authentication example |
| 3 |
|
| 4 |
This example demonstrates how to protect Flask endpoints with token |
| 5 |
authentication, using JWT tokens. To use this example you need to install the |
| 6 |
PyJWT library: |
| 7 |
|
| 8 |
pip install pyjwt |
| 9 |
|
| 10 |
When this application starts, a token is generated for each of the two users. |
| 11 |
To gain access, you can use a command line HTTP client such as curl, passing |
| 12 |
one of the tokens: |
| 13 |
|
| 14 |
curl -X GET -H "Authorization: Bearer <jws-token>" http://localhost:5000/ |
| 15 |
|
| 16 |
The response should include the username, which is obtained from the token. The |
| 17 |
tokens have a validity time of one hour, after which they will be rejected. |
| 18 |
""" |
| 19 |
from time import time |
| 20 |
from flask import Flask |
| 21 |
from flask_httpauth import HTTPTokenAuth |
| 22 |
import jwt |
| 23 |
|
| 24 |
|
| 25 |
app = Flask(__name__) |
| 26 |
app.config['SECRET_KEY'] = 'top secret!' |
| 27 |
|
| 28 |
auth = HTTPTokenAuth('Bearer') |
| 29 |
|
| 30 |
|
| 31 |
users = ['john', 'susan'] |
| 32 |
for user in users: |
| 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 |
@auth.verify_token |
| 39 |
def verify_token(token): |
| 40 |
try: |
| 41 |
data = jwt.decode(token, app.config['SECRET_KEY'], |
| 42 |
algorithms=['HS256']) |
| 43 |
except: # noqa: E722 |
| 44 |
return False |
| 45 |
if 'username' in data: |
| 46 |
return data['username'] |
| 47 |
|
| 48 |
|
| 49 |
@app.route('/') |
| 50 |
@auth.login_required |
| 51 |
def index(): |
| 52 |
return "Hello, %s!" % auth.current_user() |
| 53 |
|
| 54 |
|
| 55 |
if __name__ == '__main__': |
| 56 |
app.run() |