|
2 | 2 |
|
3 | 3 | from flask import Flask |
4 | 4 | from flask import jsonify |
5 | | -from flask import request |
6 | 5 |
|
7 | 6 | from flask_jwt_extended import create_access_token |
8 | 7 | from flask_jwt_extended import get_jwt |
|
15 | 14 | jwt = JWTManager(app) |
16 | 15 |
|
17 | 16 |
|
18 | | -# Here is a custom decorator that verifies the JWT is present in |
19 | | -# the request, as well as insuring that this user has a role of |
20 | | -# `admin` in the access token |
21 | | -def admin_required(fn): |
22 | | - @wraps(fn) |
23 | | - def wrapper(*args, **kwargs): |
24 | | - verify_jwt_in_request() |
25 | | - claims = get_jwt() |
26 | | - if claims["roles"] != "admin": |
27 | | - return jsonify(msg="Admins only!"), 403 |
28 | | - else: |
29 | | - return fn(*args, **kwargs) |
30 | | - |
31 | | - return wrapper |
| 17 | +# Here is a custom decorator that verifies the JWT is present in the request, |
| 18 | +# as well as insuring that the JWT has a claim indicating that this user is |
| 19 | +# an administrator |
| 20 | +def admin_required(): |
| 21 | + def wrapper(fn): |
| 22 | + @wraps(fn) |
| 23 | + def decorator(*args, **kwargs): |
| 24 | + verify_jwt_in_request() |
| 25 | + claims = get_jwt() |
| 26 | + if claims["is_administrator"]: |
| 27 | + return fn(*args, **kwargs) |
| 28 | + else: |
| 29 | + return jsonify(msg="Admins only!"), 403 |
32 | 30 |
|
| 31 | + return decorator |
33 | 32 |
|
34 | | -@jwt.additional_claims_loader |
35 | | -def add_claims_to_access_token(identity): |
36 | | - if identity == "admin": |
37 | | - return {"roles": "admin"} |
38 | | - else: |
39 | | - return {"roles": "peasant"} |
| 33 | + return wrapper |
40 | 34 |
|
41 | 35 |
|
42 | 36 | @app.route("/login", methods=["POST"]) |
43 | 37 | def login(): |
44 | | - username = request.json.get("username", None) |
45 | | - access_token = create_access_token(username) |
| 38 | + access_token = create_access_token( |
| 39 | + "admin_user", additional_claims={"is_administrator": True} |
| 40 | + ) |
46 | 41 | return jsonify(access_token=access_token) |
47 | 42 |
|
48 | 43 |
|
49 | 44 | @app.route("/protected", methods=["GET"]) |
50 | | -@admin_required |
| 45 | +@admin_required() |
51 | 46 | def protected(): |
52 | | - return jsonify(secret_message="go banana!") |
| 47 | + return jsonify(foo="bar") |
53 | 48 |
|
54 | 49 |
|
55 | 50 | if __name__ == "__main__": |
|
0 commit comments