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 existingAuthManagerobject, 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
JWTwith the claims provided.- Parameters:
subject (
str|int) – Value for thesubclaim.scope (
str|dict) – Optionalscopeclaim for authorizations. Defaults toNone.**kwargs – Any additional claims to add to the JWT.
- Returns:
Token with a
typeclaim 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
JWTobject.- Parameters:
signed_token (
str) – A properly encoded JWT.- Returns:
The signed and encoded JWT as a
JWTobject.- Return type:
- Raises:
InvalidTokenError – If the
signed_tokenparameter 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
authtoken.- Type:
int
- default_refresh_max_age: int = 604800¶
The default max age for a
refreshtoken.- Type:
int
- init_app(app: Flask) None¶
Initializes an
AuthManagerwith 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
JWTwith the claims provided.- Parameters:
subject (
str|int) – Value for thesubclaim.- Returns:
Token with a
typeclaim of “refresh”.- Return type:
Example:
refresh_token = auth_manager.refresh_token(subject="Flask_PyJWT")
- verify_token(token: JWT | str) bool¶
Verifies that a
JWTor encoded JWT has been signed by thisAuthManagerand 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
scopecan be checked for authorization. Additionalkwargscan 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
routedecorator.- 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 thelocationis set to “cookies”. Defaults toNone.scope (
str|int|dict) – Optional claims to check in the token’sscopefor authorization. Defaults toNone.override (
dict) – Optional claims to check for authorization. Ifoverrideis set, and the claims inoverrideare present and valid, thescopeand additional**kwargsparameter(s) is ignored. Defaults toNone.**kwargs – Additional claims that must be present on the token for authorization.
- Raises:
ValueError – If
token_typeorlocationis not a valid value.AttributeError – If
cookie_nameis 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
subandtypeby 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
Noneif 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
Noneif the JWT has not been signed.- Return type:
int|None
- classmethod from_signed_token(signed_token: str) JWT¶
Converts a signed JWT into a
JWTobject- Parameters:
signed_token (
str) – A valid, signed, and encoded JWT.- Returns:
A
JWTobject containing the data from thesigned_tokenparameter.- Return type:
- Raises:
InvalidTokenError – If the
signed_tokenparameter 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
Noneif the JWT has not been signed.- Return type:
int|None
- is_signed() bool¶
Returns whether this JWT has been signed.
- Returns:
True if
signedattribute is notNone, False if not.- Return type:
bool
- property iss: int | None¶
The issuer property of the JWT.
- Returns:
Issuer of the JWT, or
Noneif 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
Noneif 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
Noneif there is noscopeclaim.- Return type:
str|int|dict|None
- sign(auth_data: AuthData) str¶
Signs this JWT, setting the
iatto be the current time when this function is called.Attributes of
iss,exp, andmax_ageare also set based on theAuthDatasigner 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) – TheAuthTypethat 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_typeparameter’s secret_type.issuer (
str) – Identifier for who will issue a JWT.auth_max_age (
int) – The max age for a JWT withTokenTypeofAUTH.refresh_max_age (
int) – The max age for a JWT withTokenTypeofREFRESH.public_key (
bytes|None) – The public key used to verify signed JWTs if theAuthTypeisRS256orRS512.
- secret¶
The secret key used to sign a JWT. Must match the type specified in the
auth_typeparameter’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
AuthTypeisRS256orRS512. 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
secretparameter’s type does not match the type specified in theauth_typeparameter’s secret type.
- algorithm() str¶
Returns the algorithm type used.
- Returns:
nameattribute of theauth_typeattribute.
- 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, andexpkey to the claims dict.- Parameters:
token_type (
TokenType) – The type of token to sign, which determines theexpvalue.claims (
dict) – The claims to sign and extend.
- Returns:
The
claimsextended with “iss”, “iat”, and “exp”. An “rid” claim is added if thetoken_typeisTokenType.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
signerattribute has not been set on anAuthManagerobject.
MissingConfigError¶
- class flask_pyjwt.exceptions.MissingConfigError(config_value: str)¶
Raised when a config value is missing from an
AuthManagerobject.- 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
AuthManagerobject.- Parameters:
config_value (
str) – The config value that raised this exception.message (
str) – A message describing what the valid config values are.