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 existingAuthManager
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 forsigning JWTs created by this auth manager.
Optional config values include:
JWT_AUTHMAXAGE
(int
): How long auth JWTs created by thisauth manager are valid for.
JWT_REFRESHMAXAGE
(int
): How long refresh JWTs createdby this auth manager are valid for.
JWT_PUBLICKEY
(str
|bytes
): The public key used forverifying 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:
MissingConfigError – If a required config key is missing from the flask app.
InvalidConfigError – If a config key’s value is of the wrong type or an unacceptable value.
- 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 thesub
claim.scope (
str
|dict
) – Optionalscope
claim for authorizations. Defaults toNone
.**kwargs – Any additional claims to add to the JWT.
- Returns:
Token with a
type
claim of “auth”.- Return type:
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:
- 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 inapp
, and attaches itself to the flask app.- Parameters:
app (
Flask
) – A flask application to retrieve config values from.- Raises:
MissingConfigError – If a required config key is missing from the flask app.
InvalidConfigError – If a config key’s value is of the wrong type or an unacceptable value.
- refresh_token(subject: str | int) JWT ¶
Generates a new
JWT
with the claims provided.- Parameters:
subject (
str
|int
) – Value for thesub
claim.- Returns:
Token with a
type
claim of “refresh”.- Return type:
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 thisAuthManager
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
, andiss
, 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. Additionalkwargs
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 thelocation
is set to “cookies”. Defaults toNone
.scope (
str
|int
|dict
) – Optional claims to check in the token’sscope
for authorization. Defaults toNone
.override (
dict
) – Optional claims to check for authorization. Ifoverride
is set, and the claims inoverride
are present and valid, thescope
and additional**kwargs
parameter(s) is ignored. Defaults toNone
.**kwargs – Additional claims that must be present on the token for authorization.
- Raises:
ValueError – If
token_type
orlocation
is not a valid value.AttributeError – If
cookie_name
is not present whenlocation == "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¶
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:
- claims¶
The claims of the JWT. Includes
sub
andtype
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 thesigned_token
parameter.- Return type:
- 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 notNone
, 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 noscope
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
, andmax_age
are also set based on theAuthData
signer object used in this function.
- 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
) – TheAuthType
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 theauth_type
parameter’s secret_type.issuer (
str
) – Identifier for who will issue a JWT.auth_max_age (
int
) – The max age for a JWT withTokenType
ofAUTH
.refresh_max_age (
int
) – The max age for a JWT withTokenType
ofREFRESH
.public_key (
bytes
|None
) – The public key used to verify signed JWTs if theAuthType
isRS256
orRS512
.
- 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
- public_key¶
The public key used to verify signed JWTs if the
AuthType
isRS256
orRS512
. 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 theauth_type
parameter’s secret type.
- algorithm() str ¶
Returns the algorithm type used.
- Returns:
name
attribute of theauth_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
, andexp
key to the claims dict.- Parameters:
token_type (
TokenType
) – The type of token to sign, which determines theexp
value.claims (
dict
) – The claims to sign and extend.
- Returns:
The
claims
extended with “iss”, “iat”, and “exp”. An “rid” claim is added if thetoken_type
isTokenType.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 anAuthManager
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.