API Documentation

This is the documentation for all of the API that is exported in this extension.

Configuring Flask-JWT-Extended

class flask_jwt_extended.JWTManager(app: Flask | None = None, add_context_processor: bool = False)[source]

An object used to hold JWT settings and callback functions for the Flask-JWT-Extended extension.

Instances of JWTManager are not bound to specific apps, so you can create one in the main body of your code and then bind it to your app in a factory function.

additional_claims_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to add additional claims when creating a JWT. The claims returned by this function will be merged with any claims passed in via the additional_claims argument to create_access_token() or create_refresh_token().

The decorated function must take one argument.

The argument is the identity that was used when creating a JWT.

The decorated function must return a dictionary of claims to add to the JWT.

additional_headers_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to add additional headers when creating a JWT. The headers returned by this function will be merged with any headers passed in via the additional_headers argument to create_access_token() or create_refresh_token().

The decorated function must take one argument.

The argument is the identity that was used when creating a JWT.

The decorated function must return a dictionary of headers to add to the JWT.

decode_key_loader(callback: Callable) Callable[source]

This decorator sets the callback function for dynamically setting the JWT decode key based on the UNVERIFIED contents of the token. Think carefully before using this functionality, in most cases you probably don’t need it.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the unverified JWT.

The second argument is a dictionary containing the payload data of the unverified JWT.

The decorated function must return a string that is used to decode and verify the token.

encode_key_loader(callback: Callable) Callable[source]

This decorator sets the callback function for dynamically setting the JWT encode key based on the tokens identity. Think carefully before using this functionality, in most cases you probably don’t need it.

The decorated function must take one argument.

The argument is the identity used to create this JWT.

The decorated function must return a string which is the secrete key used to encode the JWT.

expired_token_loader(callback: Callable) Callable[source]

This decorator sets the callback function for returning a custom response when an expired JWT is encountered.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return a Flask Response.

init_app(app: Flask, add_context_processor: bool = False) None[source]

Register this extension with the flask app.

Parameters:
  • app – The Flask Application object

  • add_context_processor – Controls if current_user is should be added to flasks template context (and thus be available for use in Jinja templates). Defaults to False.

invalid_token_loader(callback: Callable) Callable[source]

This decorator sets the callback function for returning a custom response when an invalid JWT is encountered.

This decorator sets the callback function that will be used if an invalid JWT attempts to access a protected endpoint.

The decorated function must take one argument.

The argument is a string which contains the reason why a token is invalid.

The decorated function must return a Flask Response.

needs_fresh_token_loader(callback: Callable) Callable[source]

This decorator sets the callback function for returning a custom response when a valid and non-fresh token is used on an endpoint that is marked as fresh=True.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return a Flask Response.

revoked_token_loader(callback: Callable) Callable[source]

This decorator sets the callback function for returning a custom response when a revoked token is encountered.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return a Flask Response.

token_in_blocklist_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to check if a JWT has been revoked.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must be return True if the token has been revoked, False otherwise.

token_verification_failed_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to return a custom response when the claims verification check fails.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return a Flask Response.

token_verification_loader(callback: Callable) Callable[source]

This decorator sets the callback function used for custom verification of a valid JWT.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return True if the token is valid, or False otherwise.

unauthorized_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to return a custom response when no JWT is present.

The decorated function must take one argument.

The argument is a string that explains why the JWT could not be found.

The decorated function must return a Flask Response.

user_identity_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to convert an identity to a JSON serializable format when creating JWTs. This is useful for using objects (such as SQLAlchemy instances) as the identity when creating your tokens.

The decorated function must take one argument.

The argument is the identity that was used when creating a JWT.

The decorated function must return JSON serializable data.

user_lookup_error_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to return a custom response when loading a user via user_lookup_loader() fails.

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function must return a Flask Response.

user_lookup_loader(callback: Callable) Callable[source]

This decorator sets the callback function used to convert a JWT into a python object that can be used in a protected endpoint. This is useful for automatically loading a SQLAlchemy instance based on the contents of the JWT.

The object returned from this function can be accessed via current_user or get_current_user()

The decorated function must take two arguments.

The first argument is a dictionary containing the header data of the JWT.

The second argument is a dictionary containing the payload data of the JWT.

The decorated function can return any python object, which can then be accessed in a protected endpoint. If an object cannot be loaded, for example if a user has been deleted from your database, None must be returned to indicate that an error occurred loading the user.

Verify Tokens in Request

flask_jwt_extended.jwt_required(optional: bool = False, fresh: bool = False, refresh: bool = False, locations: str | Sequence | None = None, verify_type: bool = True, skip_revocation_check: bool = False) Any[source]

A decorator to protect a Flask endpoint with JSON Web Tokens.

Any route decorated with this will require a valid JWT to be present in the request (unless optional=True, in which case no JWT is also valid) before the endpoint can be called.

Parameters:
  • optional – If True, allow the decorated endpoint to be accessed if no JWT is present in the request. Defaults to False.

  • fresh – If True, require a JWT marked with fresh to be able to access this endpoint. Defaults to False.

  • refresh – If True, requires a refresh JWT to access this endpoint. If False, requires an access JWT to access this endpoint. Defaults to False.

  • locations – A location or list of locations to look for the JWT in this request, for example 'headers' or ['headers', 'cookies']. Defaults to None which indicates that JWTs will be looked for in the locations defined by the JWT_TOKEN_LOCATION configuration option.

  • verify_type – If True, the token type (access or refresh) will be checked according to the refresh argument. If False, type will not be checked and both access and refresh tokens will be accepted.

  • skip_revocation_check – If True, revocation status of the token will be not checked. If False, revocation status of the token will be checked.

flask_jwt_extended.verify_jwt_in_request(optional: bool = False, fresh: bool = False, refresh: bool = False, locations: str | Sequence | None = None, verify_type: bool = True, skip_revocation_check: bool = False) Tuple[dict, dict] | None[source]

Verify that a valid JWT is present in the request, unless optional=True in which case no JWT is also considered valid.

Parameters:
  • optional – If True, do not raise an error if no JWT is present in the request. Defaults to False.

  • fresh – If True, require a JWT marked as fresh in order to be verified. Defaults to False.

  • refresh – If True, requires a refresh JWT to access this endpoint. If False, requires an access JWT to access this endpoint. Defaults to False

  • locations – A location or list of locations to look for the JWT in this request, for example 'headers' or ['headers', 'cookies']. Defaults to None which indicates that JWTs will be looked for in the locations defined by the JWT_TOKEN_LOCATION configuration option.

  • verify_type – If True, the token type (access or refresh) will be checked according to the refresh argument. If False, type will not be checked and both access and refresh tokens will be accepted.

  • skip_revocation_check – If True, revocation status of the token will be not checked. If False, revocation status of the token will be checked.

Returns:

A tuple containing the jwt_header and the jwt_data if a valid JWT is present in the request. If optional=True and no JWT is in the request, None will be returned instead. Raise an exception if an invalid JWT is in the request.

Utilities

flask_jwt_extended.create_access_token(identity: Any, fresh: bool | float | timedelta = False, expires_delta: Literal[False] | timedelta | None = None, additional_claims=None, additional_headers=None)[source]

Create a new access token.

Parameters:
  • identity – The identity of this token. It can be any data that is json serializable. You can use user_identity_loader() to define a callback function to convert any object passed in into a json serializable format.

  • fresh

    If this token should be marked as fresh, and can thus access endpoints protected with @jwt_required(fresh=True). Defaults to False.

    This value can also be a datetime.timedelta, which indicate how long this token will be considered fresh.

  • expires_delta – A datetime.timedelta for how long this token should last before it expires. Set to False to disable expiration. If this is None, it will use the JWT_ACCESS_TOKEN_EXPIRES config value (see Configuration Options)

  • additional_claims – Optional. A hash of claims to include in the access token. These claims are merged into the default claims (exp, iat, etc) and claims returned from the additional_claims_loader() callback. On conflict, these claims take precedence.

  • headers – Optional. A hash of headers to include in the access token. These headers are merged into the default headers (alg, typ) and headers returned from the additional_headers_loader() callback. On conflict, these headers take precedence.

Returns:

An encoded access token

flask_jwt_extended.create_refresh_token(identity: Any, expires_delta: Literal[False] | timedelta | None = None, additional_claims=None, additional_headers=None)[source]

Create a new refresh token.

Parameters:
  • identity – The identity of this token. It can be any data that is json serializable. You can use user_identity_loader() to define a callback function to convert any object passed in into a json serializable format.

  • expires_delta – A datetime.timedelta for how long this token should last before it expires. Set to False to disable expiration. If this is None, it will use the JWT_REFRESH_TOKEN_EXPIRES config value (see Configuration Options)

  • additional_claims – Optional. A hash of claims to include in the refresh token. These claims are merged into the default claims (exp, iat, etc) and claims returned from the additional_claims_loader() callback. On conflict, these claims take precedence.

  • headers – Optional. A hash of headers to include in the refresh token. These headers are merged into the default headers (alg, typ) and headers returned from the additional_headers_loader() callback. On conflict, these headers take precedence.

Returns:

An encoded refresh token

flask_jwt_extended.current_user

A LocalProxy for accessing the current user. Roughly equilivant to get_current_user()

flask_jwt_extended.decode_token(encoded_token: str, csrf_value: str | None = None, allow_expired: bool = False) dict[source]

Returns the decoded token (python dict) from an encoded JWT. This does all the checks to ensure that the decoded token is valid before returning it.

This will not fire the user loader callbacks, save the token for access in protected endpoints, checked if a token is revoked, etc. This is puerly used to ensure that a JWT is valid.

Parameters:
  • encoded_token – The encoded JWT to decode.

  • csrf_value – Expected CSRF double submit value (optional).

  • allow_expired – If True, do not raise an error if the JWT is expired. Defaults to False

Returns:

Dictionary containing the payload of the JWT decoded JWT.

flask_jwt_extended.get_csrf_token(encoded_token: str) str[source]

Returns the CSRF double submit token from an encoded JWT.

Parameters:

encoded_token – The encoded JWT

Returns:

The CSRF double submit token (string)

flask_jwt_extended.get_current_user() Any[source]

In a protected endpoint, this will return the user object for the JWT that is accessing the endpoint.

This is only usable if user_lookup_loader() is configured. If the user loader callback is not being used, this will raise an error.

If no JWT is present due to jwt_required(optional=True), None is returned.

Returns:

The current user object for the JWT in the current request

flask_jwt_extended.get_jti(encoded_token: str) str | None[source]

Returns the JTI (unique identifier) of an encoded JWT

Parameters:

encoded_token – The encoded JWT to get the JTI from.

Returns:

The JTI (unique identifier) of a JWT, if it is present.

flask_jwt_extended.get_jwt() dict[source]

In a protected endpoint, this will return the python dictionary which has the payload of the JWT that is accessing the endpoint. If no JWT is present due to jwt_required(optional=True), an empty dictionary is returned.

Returns:

The payload (claims) of the JWT in the current request

flask_jwt_extended.get_jwt_header() dict[source]

In a protected endpoint, this will return the python dictionary which has the header of the JWT that is accessing the endpoint. If no JWT is present due to jwt_required(optional=True), an empty dictionary is returned.

Returns:

The headers of the JWT in the current request

flask_jwt_extended.get_jwt_identity() Any[source]

In a protected endpoint, this will return the identity of the JWT that is accessing the endpoint. If no JWT is present due to jwt_required(optional=True), None is returned.

Returns:

The identity of the JWT in the current request

flask_jwt_extended.get_unverified_jwt_headers(encoded_token: str) dict[source]

Returns the Headers of an encoded JWT without verifying the signature of the JWT.

Parameters:

encoded_token – The encoded JWT to get the Header from.

Returns:

JWT header parameters as python dict()

flask_jwt_extended.set_access_cookies(response: Response, encoded_access_token: str, max_age=None, domain=None) None[source]

Modifiy a Flask Response to set a cookie containing the access JWT. Also sets the corresponding CSRF cookies if JWT_CSRF_IN_COOKIES is True (see Configuration Options)

Parameters:
  • response – A Flask Response object.

  • encoded_access_token – The encoded access token to set in the cookies.

  • max_age – The max age of the cookie. If this is None, it will use the JWT_SESSION_COOKIE option (see Configuration Options). Otherwise, it will use this as the cookies max-age and the JWT_SESSION_COOKIE option will be ignored. Values should be the number of seconds (as an integer).

  • domain – The domain of the cookie. If this is None, it will use the JWT_COOKIE_DOMAIN option (see Configuration Options). Otherwise, it will use this as the cookies domain and the JWT_COOKIE_DOMAIN option will be ignored.

flask_jwt_extended.set_refresh_cookies(response: Response, encoded_refresh_token: str, max_age: int | None = None, domain: str | None = None) None[source]

Modifiy a Flask Response to set a cookie containing the refresh JWT. Also sets the corresponding CSRF cookies if JWT_CSRF_IN_COOKIES is True (see Configuration Options)

Parameters:
  • response – A Flask Response object.

  • encoded_refresh_token – The encoded refresh token to set in the cookies.

  • max_age – The max age of the cookie. If this is None, it will use the JWT_SESSION_COOKIE option (see Configuration Options). Otherwise, it will use this as the cookies max-age and the JWT_SESSION_COOKIE option will be ignored. Values should be the number of seconds (as an integer).

  • domain – The domain of the cookie. If this is None, it will use the JWT_COOKIE_DOMAIN option (see Configuration Options). Otherwise, it will use this as the cookies domain and the JWT_COOKIE_DOMAIN option will be ignored.

flask_jwt_extended.unset_access_cookies(response: Response, domain: str | None = None) None[source]

Modifiy a Flask Response to delete the cookie containing an access JWT. Also deletes the corresponding CSRF cookie if applicable.

Parameters:
  • response – A Flask Response object

  • domain – The domain of the cookie. If this is None, it will use the JWT_COOKIE_DOMAIN option (see Configuration Options). Otherwise, it will use this as the cookies domain and the JWT_COOKIE_DOMAIN option will be ignored.

flask_jwt_extended.unset_jwt_cookies(response: Response, domain: str | None = None) None[source]

Modifiy a Flask Response to delete the cookies containing access or refresh JWTs. Also deletes the corresponding CSRF cookies if applicable.

Parameters:

response – A Flask Response object

flask_jwt_extended.unset_refresh_cookies(response: Response, domain: str | None = None) None[source]

Modifiy a Flask Response to delete the cookie containing a refresh JWT. Also deletes the corresponding CSRF cookie if applicable.

Parameters:
  • response – A Flask Response object

  • domain – The domain of the cookie. If this is None, it will use the JWT_COOKIE_DOMAIN option (see Configuration Options). Otherwise, it will use this as the cookies domain and the JWT_COOKIE_DOMAIN option will be ignored.