Skip to content

Commit 79f69ce

Browse files
author
Landon Gilbert-Bland
committed
Finish updating existing documentation
1 parent b3adde8 commit 79f69ce

File tree

4 files changed

+25
-133
lines changed

4 files changed

+25
-133
lines changed

docs/changing_default_behavior.rst

Lines changed: 9 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,90 +1,15 @@
11
Changing Default Behaviors
22
==========================
33

4-
NOTE: THIS DOCUMENTATION HAS NOT YET BEEN UPDATED
5-
6-
7-
Changing callback functions
8-
~~~~~~~~~~~~~~~~~~~~~~~~~~~
9-
10-
We provide what we think are sensible behaviors when attempting to access a
11-
protected endpoint. If the access token is not valid for any reason (missing,
12-
expired, tampered with, etc) we will return json in the format of {'msg': 'why
13-
accessing endpoint failed'} along with an appropriate http status code
14-
(generally 401 or 422). However, you may want to customize what you return in
15-
some situations. We can do that with the jwt_manager loader functions.
16-
4+
This extension provides sensible default behaviors. For example, if an expired
5+
token attempts to access a protected endpoint, you will get a JSON response back
6+
like ``{"msg": "Token has expired"}`` and a 401 status code. However there may
7+
be various behaviors of this extension that you want to customize to your
8+
application's needs. We can do that with the various loader functions. Here is
9+
an example of how to do that.
1710

1811
.. literalinclude:: ../examples/loaders.py
1912

20-
Here are the possible loader functions. Click on the links for a more
21-
more details about what arguments your callback functions should expect
22-
and what the return values of your callback functions need to be.
23-
24-
.. list-table::
25-
:header-rows: 1
26-
27-
* - Loader Decorator
28-
- Description
29-
* - :meth:`~flask_jwt_extended.JWTManager.token_verification_loader`
30-
- Function that is called to do additional verifcations on the jwt data. Must return True or False
31-
* - :meth:`~flask_jwt_extended.JWTManager.token_verification_failed_loader`
32-
- Function that is called when the user claims verification callback returns False
33-
* - :meth:`~flask_jwt_extended.JWTManager.decode_key_loader`
34-
- Function that is called to get the decode key before verifying a token
35-
* - :meth:`~flask_jwt_extended.JWTManager.encode_key_loader`
36-
- Function that is called to get the encode key before creating a token
37-
* - :meth:`~flask_jwt_extended.JWTManager.expired_token_loader`
38-
- Function to call when an expired token accesses a protected endpoint
39-
* - :meth:`~flask_jwt_extended.JWTManager.invalid_token_loader`
40-
- Function to call when an invalid token accesses a protected endpoint
41-
* - :meth:`~flask_jwt_extended.JWTManager.needs_fresh_token_loader`
42-
- Function to call when a non-fresh token accesses a :func:`~flask_jwt_extended.jwt_required` endpoint
43-
* - :meth:`~flask_jwt_extended.JWTManager.revoked_token_loader`
44-
- Function to call when a revoked token accesses a protected endpoint
45-
* - :meth:`~flask_jwt_extended.JWTManager.token_in_blocklist_loader`
46-
- Function that is called to check if a token has been revoked
47-
* - :meth:`~flask_jwt_extended.JWTManager.unauthorized_loader`
48-
- Function to call when a request with no JWT accesses a protected endpoint
49-
* - :meth:`~flask_jwt_extended.JWTManager.user_lookup_loader`
50-
- Function to call to load a user object when token accesses a protected endpoint
51-
* - :meth:`~flask_jwt_extended.JWTManager.user_lookup_error_loader`
52-
- Function that is called when the user_lookup callback function returns `None`
53-
54-
Dynamic token expires time
55-
~~~~~~~~~~~~~~~~~~~~~~~~~~
56-
57-
You can also change the expires time for a token via the `expires_delta` kwarg
58-
in the :func:`~flask_jwt_extended.create_refresh_token` and
59-
:func:`~flask_jwt_extended.create_access_token` functions. This takes
60-
a `datetime.timedelta` and overrides the `JWT_REFRESH_TOKEN_EXPIRES` and
61-
`JWT_ACCESS_TOKEN_EXPIRES` settings (see :ref:`Configuration Options`).
62-
63-
This can be useful if you have different use cases for different tokens.
64-
For example, you might use short lived access tokens used in your web
65-
application, but you allow the creation of long lived access tokens that other
66-
developers can generate and use to interact with your api in their programs.
67-
You could accomplish this like such:
68-
69-
.. code-block:: python
70-
71-
@app.route('/create-dev-token', methods=['POST'])
72-
@jwt_required
73-
def create_dev_token():
74-
username = get_jwt_identity()
75-
expires = datetime.timedelta(days=365)
76-
token = create_access_token(username, expires_delta=expires)
77-
return jsonify({'token': token}), 201
78-
79-
You can even disable expiration by setting `expires_delta` to `False`:
80-
81-
.. code-block:: python
82-
83-
@app.route('/create-api-token', methods=['POST'])
84-
@jwt_required
85-
def create_api_token():
86-
username = get_jwt_identity()
87-
token = create_access_token(username, expires_delta=False)
88-
return jsonify({'token': token}), 201
89-
90-
Note that in this case, you should enable token revoking (see :ref:`Blocklist and Token Revoking`).
13+
There are all sorts of callbacks that can be defined to customize the behaviors
14+
of this extension. See the :ref:`Configuring Flask-JWT-Extended` API Documentation
15+
for a full list of callback functions that are available in this extension.

docs/index.rst

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,6 @@
66
Flask-JWT-Extended's Documentation
77
==================================
88

9-
..
10-
- Installation
11-
- Basic Usage
12-
- Automatic User Loading
13-
- Adding claims to JWTs
14-
- Optional Endpoints
15-
- Token Locations
16-
- Headers
17-
- Cookies
18-
- JSON Body
19-
- Query String
20-
- locations kwarg for decorator
21-
- Refresh Tokens
22-
- Implict refreshing with cookies
23-
- Prefered for browsers
24-
- Explict refreshing with refresh tokesn
25-
- Prefered for non-browsers
26-
- Fresh Token pattern
27-
- Here or coupled with refresh tokens?
28-
- Blocklist and Token Revoking
29-
- Configuratino Options
30-
- Modifying Behaviors with Callback Functions
31-
- Custom Decorators
32-
- API Documentation
33-
349
.. toctree::
3510
:maxdepth: 2
3611

docs/options.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ General Options:
3636
If set to ``False`` tokens will never expire. **This is dangerous and should
3737
be avoided in most case**
3838

39+
This can be overridden on a per token basis by passing the ``expires_delta``
40+
argument to :func:`flask_jwt_extended.create_access_token`
41+
3942
Default: ``datetime.timedelta(minutes=15)``
4043

4144

@@ -49,6 +52,9 @@ General Options:
4952
If set to ``False`` tokens will never expire. **This is dangerous and should
5053
be avoided in most case**
5154

55+
This can be overridden on a per token basis by passing the ``expires_delta``
56+
argument to :func:`flask_jwt_extended.create_refresh_token`
57+
5258
Default: ``datetime.timedelta(days=30)``
5359

5460

examples/loaders.py

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from flask import Flask
22
from flask import jsonify
3-
from flask import request
43

54
from flask_jwt_extended import create_access_token
65
from flask_jwt_extended import jwt_required
@@ -12,39 +11,26 @@
1211
jwt = JWTManager(app)
1312

1413

15-
# Using the expired_token_loader decorator, we will now call
16-
# this function whenever an expired but otherwise valid access
17-
# token attempts to access an endpoint
14+
# Set a callback function to return a custom response whenever an expired
15+
# token attempts to access a protected route. This particular callback function
16+
# takes the jwt_header and jwt_payload as arguments, and must return a Flask
17+
# response. Check the API documentation to see the required argument and return
18+
# values for other callback functions.
1819
@jwt.expired_token_loader
19-
def my_expired_token_callback(expired_token):
20-
token_type = expired_token["type"]
21-
return (
22-
jsonify(
23-
{
24-
"status": 401,
25-
"sub_status": 42,
26-
"msg": "The {} token has expired".format(token_type),
27-
}
28-
),
29-
401,
30-
)
20+
def my_expired_token_callback(jwt_header, jwt_payload):
21+
return jsonify(code="dave", err="I can't let you do that"), 401
3122

3223

3324
@app.route("/login", methods=["POST"])
3425
def login():
35-
username = request.json.get("username", None)
36-
password = request.json.get("password", None)
37-
if username != "test" or password != "test":
38-
return jsonify({"msg": "Bad username or password"}), 401
39-
40-
ret = {"access_token": create_access_token(username)}
41-
return jsonify(ret), 200
26+
access_token = create_access_token("example_user")
27+
return jsonify(access_token=access_token)
4228

4329

4430
@app.route("/protected", methods=["GET"])
4531
@jwt_required
4632
def protected():
47-
return jsonify({"hello": "world"}), 200
33+
return jsonify(hello="world")
4834

4935

5036
if __name__ == "__main__":

0 commit comments

Comments
 (0)