API

AuthManager Object

class flask_pyjwt.manager.AuthManager(app: Flask | None = None, dotenv_path: str | None = None)

The main object used for interfacing with Flask_PyJWT.

Includes methods for creating auth and refresh tokens, and verifying tokens. Can be initialized using the application factory pattern by calling the init_app() method on an existing AuthManager object, or by passing the Flask app directly into the constructor.

Required config values are:

  • JWT_ISSUER (str): The issuer of JWTs created by this auth manager.

  • JWT_AUTHTYPE (str): The type of auth to use (ex: HS256)

    for keys created by this auth manager.

  • JWT_SECRET (str | bytes): The secret key used for

    signing JWTs created by this auth manager.

Optional config values include:

  • JWT_AUTHMAXAGE (int): How long auth JWTs created by this

    auth manager are valid for.

  • JWT_REFRESHMAXAGE (int): How long refresh JWTs created

    by this auth manager are valid for.

  • JWT_PUBLICKEY (str | bytes): The public key used for

    verifying signed JWTs created by this auth manager if the RSA algorithm is used.

Initializing:

app = Flask(__name__)
auth_manager = AuthManager(app)
# or alternatively:
auth_manager = AuthManager()
auth_manager.init_app(app)

Example Usage:

@app.route("/token/<str:user_id>", methods=["POST"])
def index(user_id: str):
    auth_token = auth_manager.auth_token(
        subject=user_id,
        scope={"admin": True},
        custom_claim="Flask_PyJWT"
    )
    return {"auth_token": auth_token.signed}
Parameters:
  • app (Flask) – A flask application to retrieve config values from.

  • dotenv_path (str | None) – The absolute or relative path to a .env file to load configuration variables from.

Raises:
auth_token(subject: str | int, scope: str | dict | None = None, **kwargs: str | int | dict | None) JWT

Generates a new JWT with the claims provided.

Parameters:
  • subject (str | int) – Value for the sub claim.

  • scope (str | dict) – Optional scope claim for authorizations. Defaults to None.

  • **kwargs – Any additional claims to add to the JWT.

Returns:

Token with a type claim of “auth”.

Return type:

JWT

Example:

>>> auth_token = auth_manager.auth_token(subject="Flask_PyJWT")
>>> auth_token.is_signed()
True
static convert_token(signed_token: str) JWT

Converts a signed encoded JWT into a JWT object.

Parameters:

signed_token (str) – A properly encoded JWT.

Returns:

The signed and encoded JWT as a JWT object.

Return type:

JWT

Raises:

InvalidTokenError – If the signed_token parameter is not a valid token or does not contain the required claims “exp”, “iss”, “sub”, “iat”, and “type”.

Example:

>>> signed_encoded_token = "eyJhbG..._adQssw5c"
>>> jwt = convert_token(signed_encoded_token)
>>> print(jwt.signed)
'eyJhbG..._adQssw5c'
default_auth_max_age: int = 3600

The default max age for an auth token.

Type:

int

default_refresh_max_age: int = 604800

The default max age for a refresh token.

Type:

int

init_app(app: Flask) None

Initializes an AuthManager with the config values in app, and attaches itself to the flask app.

Parameters:

app (Flask) – A flask application to retrieve config values from.

Raises:
refresh_token(subject: str | int) JWT

Generates a new JWT with the claims provided.

Parameters:

subject (str | int) – Value for the sub claim.

Returns:

Token with a type claim of “refresh”.

Return type:

JWT

Example:

refresh_token = auth_manager.refresh_token(subject="Flask_PyJWT")
verify_token(token: JWT | str) bool

Verifies that a JWT or encoded JWT has been signed by this AuthManager and is not in an invalid format or encoding.

Parameters:

token (JWT | str) – The JWT to verify.

Returns:

True if the JWT has a valid signature, has required claims, and has the required claims of iat, exp, and iss, otherwise False.

Return type:

bool

Note

This function does NOT verify additional custom claims nor scope.

Example:

>>> auth_token = auth_manager.auth_token(subject="Flask_PyJWT")
>>> verify_token(auth_token)
True

Route Decorator

@flask_pyjwt.utils.require_token(token_type: Literal['auth', 'refresh'] = 'auth', location: Literal['header', 'cookies'] = 'header', cookie_name: str | None = None, scope: str | int | dict | None = None, override: dict | None = None, **kwargs)

Decorator function for requiring an auth or refresh token in either the header or cookies of a request.

Optionally, required claims in the scope can be checked for authorization. Additional kwargs can be supplied for checking the presence of other claims. Route variable rules can be used in the decorator by passing an argument with the name of the claim you want equal to the variable rule, and the value of the argument being equal to the name of the variable rule.

Note

This decorator must be put AFTER the flask app’s route decorator.

Parameters:
  • token_type (str) – Type of token to require (“auth” or “refresh”). Defaults to “auth”.

  • location (str) – Location of the token in the request (“header” or “cookies”). Defaults to “header”.

  • cookie_name (str) – Name of the auth/refresh token cookie. Required if the location is set to “cookies”. Defaults to None.

  • scope (str | int | dict) – Optional claims to check in the token’s scope for authorization. Defaults to None.

  • override (dict) – Optional claims to check for authorization. If override is set, and the claims in override are present and valid, the scope and additional **kwargs parameter(s) is ignored. Defaults to None.

  • **kwargs – Additional claims that must be present on the token for authorization.

Raises:
  • ValueError – If token_type or location is not a valid value.

  • AttributeError – If cookie_name is not present when location == "cookies"

Usage:

@app.route("/user/<string:user_id>", methods=["POST"])
@require_token(
    "auth",
    "cookies",
    cookie_name="auth_token",
    sub="user_id",
    custom_claim="Flask_PyJWT",
    override={"admin": True}
)
def post_user(user_id: str):
    # If a cookie called "auth_token" in the request
    # does not have a valid auth token, aborts with 401 Unauthorized.
    # If the token's scope contains "admin": True, auth token is valid.
    # Otherwise if the token doesn't have a "sub" claim of user_id
    # or "custom_claim" of "FlaskPyJWT", abort with 403 Forbidden.
    # ... some code to modify the user with id of user_id ...
    return ...

Current Token Proxy

flask_pyjwt.utils.current_token

A proxy for the current request context’s JWT object.

Usage:

@app.route("/protected_route")
@require_token("auth", "header")
def protected_route():
  # return the current token that was validated with require_token
  return {"token": current_token.signed}

JWT Object

class flask_pyjwt.jwt.JWT(token_type: TokenType, sub: str | int, scope: str | int | dict | None = None, **kwargs: str | int | dict | None)

Representation of a JWT.

Parameters:
  • token_type (TokenType) – Type of JWT, described by a TokenType.

  • sub (str | int) – Subject of the JWT.

  • scope (str | int | dict) – Used for declaring authorizations. Defaults to None.

  • **kwargs – Any extra claims to add to the JWT.

token_type

Type of JWT, described by a TokenType.

Type:

TokenType

claims

The claims of the JWT. Includes sub and type by default.

Type:

dict

signed

The signed, encoded JWT. Defaults to None.

Type:

str

typ

Type of token, which is always “JWT” in the token’s header.

Type:

str

Example:

jwt_token = JWT(
   TokenType.AUTH,
   "SomeSubjectID",
   scope={"admin": True},
   extra_key="KeyVal"
)
property alg: str | None

The algorithm property of the JWT, present in the token’s header.

Returns:

Name of the algorithm used to sign this JWT, or None if the JWT has not been signed.

Return type:

str | None

property exp: int | None

The expiration time property of the JWT.

Returns:

Expiration time, in seconds, of the JWT, or None if the JWT has not been signed.

Return type:

int | None

classmethod from_signed_token(signed_token: str) JWT

Converts a signed JWT into a JWT object

Parameters:

signed_token (str) – A valid, signed, and encoded JWT.

Returns:

A JWT object containing the data from the signed_token parameter.

Return type:

JWT

Raises:

InvalidTokenError – If the signed_token parameter is not a valid token or does not contain the required claims “exp”, “iss”, “sub”, “iat”, and “type”.

property header: dict

The header of the JWT.

Returns:

Header containing “typ” and “alg”.

Return type:

dict

property iat: int | None

The “issued at” time property of the JWT.

Returns:

Time, in seconds, the JWT was issued, or None if the JWT has not been signed.

Return type:

int | None

is_signed() bool

Returns whether this JWT has been signed.

Returns:

True if signed attribute is not None, False if not.

Return type:

bool

property iss: int | None

The issuer property of the JWT.

Returns:

Issuer of the JWT, or None if the JWT has not been signed.

Return type:

int | None

property max_age: int | None

The max age property of the JWT.

Returns:

Time, in seconds, the JWT is considered valid for, or None if the JWT has not been signed.

Return type:

int | None

property scope: str | int | dict | None

The scope property of the JWT.

Returns:

Scope of the JWT, or None if there is no scope claim.

Return type:

str | int | dict | None

sign(auth_data: AuthData) str

Signs this JWT, setting the iat to be the current time when this function is called.

Attributes of iss, exp, and max_age are also set based on the AuthData signer object used in this function.

Parameters:

auth_data (AuthData) – The AuthData object containing relevant signing information.

Returns:

An encoded JWT with valid signature containing all claims that this object possesses.

Return type:

str

property sub: str | int

The subject property of the JWT.

Returns:

Subject of the JWT.

Return type:

str | int

AuthData

class flask_pyjwt.jwt.AuthData(auth_type: AuthType, secret: bytes | str, issuer: str, auth_max_age: int, refresh_max_age: int, public_key: bytes | None = None)

Contains values used for signing a JWT.

Used as a “signer” object for JWTs.

Parameters:
  • auth_type (AuthType) – The AuthType that should be used when signing a JWT.

  • secret (bytes | str) – The secret key used to sign a JWT. Must match the type specified in the auth_type parameter’s secret_type.

  • issuer (str) – Identifier for who will issue a JWT.

  • auth_max_age (int) – The max age for a JWT with TokenType of AUTH.

  • refresh_max_age (int) – The max age for a JWT with TokenType of REFRESH.

  • public_key (bytes | None) – The public key used to verify signed JWTs if the AuthType is RS256 or RS512.

auth_type

The AuthType that should be used when signing a JWT.

Type:

AuthType

secret

The secret key used to sign a JWT. Must match the type specified in the auth_type parameter’s secret_type.

Type:

bytes | str

issuer

Identifier for who will issue a JWT.

Type:

str

auth_max_age

The max age for a JWT with TokenType of AUTH.

Type:

int

refresh_max_age

The max age for a JWT with TokenType of REFRESH.

Type:

int

public_key

The public key used to verify signed JWTs if the AuthType is RS256 or RS512. Otherwise, None.

Type:

bytes | None

Example:

auth_data = AuthData(AuthType.HS256, "SECRETKEY", "Flask_PyJWT", 120, 3600)
jwt_token = JWT(TokenType.AUTH, "SomeSubjectID")
signed_token = jwt_token.sign(auth_data)
Raises:

TypeError – If the secret parameter’s type does not match the type specified in the auth_type parameter’s secret type.

algorithm() str

Returns the algorithm type used.

Returns:

name attribute of the auth_type attribute.

extend_claims(token_type: TokenType, claims: Dict[str, str | int | dict]) Dict[str, str | int | dict]

Returns modified claims for a JWT to be signed.

Adds an iss, iat, and exp key to the claims dict.

Parameters:
  • token_type (TokenType) – The type of token to sign, which determines the exp value.

  • claims (dict) – The claims to sign and extend.

Returns:

The claims extended with “iss”, “iat”, and “exp”. An “rid” claim is added if the token_type is TokenType.REFRESH.

Return type:

dict

TokenType

class flask_pyjwt.typing.TokenType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Enum of values for valid JWT types.

Token types include “auth” and “refresh”. Auth tokens are used for short-term access to resources, and Refresh tokens are used for requesting new Auth tokens.

name

Name of the enum value.

Type:

str

value

Value that is placed inside the JWT.

Type:

str

AuthType

class flask_pyjwt.typing.AuthType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

Auth types determine how the JWT signature is created.

Tokens signed using HMAC can only be verified by those that have the secret key.

Tokens signed using RSA can only be verified by those that have the RSA public key associated with the signer’s private key.

name

Name of the enum value, this is placed inside of the JWT.

Type:

str

algorithm: str

Alias for field number 0

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=9223372036854775807, /)

Return first index of value.

Raises ValueError if the value is not present.

secret_type: Type[str] | Type[bytes]

Alias for field number 1

Exceptions

MissingSignerError

class flask_pyjwt.exceptions.MissingSignerError

Raised when the signer attribute has not been set on an AuthManager object.

MissingConfigError

class flask_pyjwt.exceptions.MissingConfigError(config_value: str)

Raised when a config value is missing from an AuthManager object.

Parameters:

config_value (str) – The config value that raised this exception.

InvalidConfigError

class flask_pyjwt.exceptions.InvalidConfigError(config_value: str, message: str)

Raised when a config value is of an incorrect type or is a value that is not allowed in an AuthManager object.

Parameters:
  • config_value (str) – The config value that raised this exception.

  • message (str) – A message describing what the valid config values are.