| 1 |
""" |
| 2 |
This example demonstrates usage of JWT token authentication with |
| 3 |
Flasgger-enabled application. |
| 4 |
|
| 5 |
Swagger version used is 3, although 2 will also run just fine. For more details |
| 6 |
on how to use Flask-JWT in general, take a look at the: |
| 7 |
https://pythonhosted.org/Flask-JWT. |
| 8 |
|
| 9 |
In this example the login credentials to call the protected API are as follows: |
| 10 |
|
| 11 |
Username: guest |
| 12 |
Password: secret |
| 13 |
|
| 14 |
In order to access protected API methods, user must first login with valid |
| 15 |
credentials. Successful login appends JWT token in login response header |
| 16 |
(name of the field is: jwt-token) - this is the field that Swagger-UI will |
| 17 |
search for when gets the response and if found - it will be automatically use |
| 18 |
its value when issuing next requests. These requests have Authorization HTTP |
| 19 |
header field with content set to: JWT token_value_goes_here (note the space |
| 20 |
between JWT and token value). |
| 21 |
|
| 22 |
Benefit of this solution is that once token is obtained, there is no need to |
| 23 |
enter it manually while working. Consider a good practice to implement method |
| 24 |
to refresh token, in order to prevent token expiration. |
| 25 |
|
| 26 |
Note however that if you want to use JWT_AUTH_HEADER_NAME - you must provide |
| 27 |
your own JWT request handler. This is because flask-jwt is not actively |
| 28 |
maintained anymore, making it impossible to add JWT_AUTH_HEADER_NAME to it. In |
| 29 |
normal circumstances, you will not need to use this field, but if you want to |
| 30 |
protect your Flasgger page in order to prevent unauthorized access to it by |
| 31 |
using basic HTTP auth on some web-server you will have to. |
| 32 |
|
| 33 |
NOTE (May 9, 2023): Python 3.11 not supported by this script |
| 34 |
(suspected flask_jwt incompatibility with python 3.11) |
| 35 |
""" |
| 36 |
|
| 37 |
|
| 38 |
import hmac |
| 39 |
from flask import Flask, jsonify, request |
| 40 |
from flask_jwt import JWT, jwt_required, current_identity, JWTError |
| 41 |
from flasgger import Swagger |
| 42 |
|
| 43 |
|
| 44 |
class User(object): |
| 45 |
def __init__(self, user_id, username, password): |
| 46 |
self.id = user_id |
| 47 |
self.username = username |
| 48 |
self.password = password |
| 49 |
|
| 50 |
def __str__(self): |
| 51 |
return "User(id='%s')" % self.id |
| 52 |
|
| 53 |
|
| 54 |
users = [ |
| 55 |
User(1, 'guest', 'secret'), |
| 56 |
] |
| 57 |
|
| 58 |
username_table = {u.username: u for u in users} |
| 59 |
userid_table = {u.id: u for u in users} |
| 60 |
|
| 61 |
|
| 62 |
def authenticate(username, password): |
| 63 |
user = username_table.get(username, None) |
| 64 |
if user and hmac.compare_digest(user.password.encode('utf-8'), password.encode('utf-8')): |
| 65 |
return user |
| 66 |
|
| 67 |
|
| 68 |
def identity(payload): |
| 69 |
user_id = payload['identity'] |
| 70 |
return userid_table.get(user_id, None) |
| 71 |
|
| 72 |
|
| 73 |
app = Flask(__name__) |
| 74 |
app.debug = True |
| 75 |
app.config["SECRET_KEY"] = "super-secret" |
| 76 |
app.config["SWAGGER"] = { |
| 77 |
"title": "Swagger JWT Authentiation App", |
| 78 |
"uiversion": 3, |
| 79 |
} |
| 80 |
app.config['JWT_AUTH_URL_RULE'] = '/api/auth' |
| 81 |
app.config['JWT_AUTH_HEADER_NAME'] = 'Jwtauthorization' |
| 82 |
app.config['JWT_AUTH_HEADER_PREFIX'] = 'Bearer' |
| 83 |
|
| 84 |
swag = Swagger(app, |
| 85 |
template={ |
| 86 |
"swagger": "2.0.0", |
| 87 |
"info": { |
| 88 |
"title": "Swagger Basic Auth App", |
| 89 |
"version": "1.0", |
| 90 |
}, |
| 91 |
"consumes": [ |
| 92 |
"application/x-www-form-urlencoded", |
| 93 |
], |
| 94 |
"produces": [ |
| 95 |
"application/json", |
| 96 |
], |
| 97 |
}, |
| 98 |
) |
| 99 |
|
| 100 |
|
| 101 |
def jwt_request_handler(): |
| 102 |
auth_header_name = app.config['JWT_AUTH_HEADER_NAME'] |
| 103 |
auth_header_value = request.headers.get(auth_header_name, None) |
| 104 |
auth_header_prefix = app.config['JWT_AUTH_HEADER_PREFIX'] |
| 105 |
|
| 106 |
if not auth_header_value: |
| 107 |
return |
| 108 |
|
| 109 |
parts = auth_header_value.split() |
| 110 |
|
| 111 |
if parts[0].lower() != auth_header_prefix.lower(): |
| 112 |
raise JWTError('Invalid JWT header', 'Unsupported authorization type') |
| 113 |
elif len(parts) == 1: |
| 114 |
raise JWTError('Invalid JWT header', 'Token missing') |
| 115 |
elif len(parts) > 2: |
| 116 |
raise JWTError('Invalid JWT header', 'Token contains spaces') |
| 117 |
|
| 118 |
return parts[1] |
| 119 |
|
| 120 |
|
| 121 |
jwt = JWT(app, authenticate, identity) |
| 122 |
jwt.request_handler(jwt_request_handler) |
| 123 |
|
| 124 |
|
| 125 |
@app.route("/login", methods=["POST"]) |
| 126 |
def login(): |
| 127 |
""" |
| 128 |
User authenticate method. |
| 129 |
--- |
| 130 |
description: Authenticate user with supplied credentials. |
| 131 |
parameters: |
| 132 |
- name: username |
| 133 |
in: formData |
| 134 |
type: string |
| 135 |
required: true |
| 136 |
- name: password |
| 137 |
in: formData |
| 138 |
type: string |
| 139 |
required: true |
| 140 |
responses: |
| 141 |
200: |
| 142 |
description: User successfully logged in. |
| 143 |
400: |
| 144 |
description: User login failed. |
| 145 |
""" |
| 146 |
try: |
| 147 |
username = request.form.get("username") |
| 148 |
password = request.form.get("password") |
| 149 |
|
| 150 |
user = authenticate(username, password) |
| 151 |
if not user: |
| 152 |
raise Exception("User not found!") |
| 153 |
|
| 154 |
resp = jsonify({"message": "User authenticated"}) |
| 155 |
resp.status_code = 200 |
| 156 |
|
| 157 |
access_token = jwt.jwt_encode_callback(user) |
| 158 |
|
| 159 |
|
| 160 |
resp.headers.extend({'jwt-token': access_token}) |
| 161 |
|
| 162 |
except Exception as e: |
| 163 |
resp = jsonify({"message": "Bad username and/or password"}) |
| 164 |
resp.status_code = 401 |
| 165 |
|
| 166 |
return resp |
| 167 |
|
| 168 |
|
| 169 |
@app.route("/protected", methods=["GET"]) |
| 170 |
@jwt_required() |
| 171 |
def protected(): |
| 172 |
""" |
| 173 |
Protected content method. |
| 174 |
--- |
| 175 |
description: Protected content method. Can not be seen without valid token. |
| 176 |
responses: |
| 177 |
200: |
| 178 |
description: User successfully accessed the content. |
| 179 |
""" |
| 180 |
resp = jsonify({"protected": "{} - you saw me!".format(current_identity)}) |
| 181 |
resp.status_code = 200 |
| 182 |
|
| 183 |
return resp |
| 184 |
|
| 185 |
|
| 186 |
if __name__ == '__main__': |
| 187 |
app.run() |