Skip to content

Auth - manager

This module provides functionality for handling JSON Web Tokens (JWT) for authentication and authorization. It defines the structure and methods required to encode and decode JWTs, as well as manage the claims associated with the tokens.

BaseJWTManager

Bases: ABC

Abstract base class for managing JSON Web Tokens (JWT). This class defines the interface for encoding and decoding JWT (RFC7519).

Info

대부분의 경우 해당 클래스의 하위 구현체를 직접 사용할 필요는 거의 없습니다.

encode abstractmethod

encode(claims, secret_key, algorithm)

Encodes the specified claims into a JSON Web Token (JWT).

PARAMETER DESCRIPTION
claims

A dictionary containing the claims to be included in the JWT.

TYPE: dict

secret_key

The secret key used to sign the JWT.

TYPE: str | bytes

algorithm

The signing algorithm to be used for the JWT.

TYPE: str

RETURNS DESCRIPTION
str

A string representation of the encoded JWT.

TYPE: str

RAISES DESCRIPTION
NotImplementedError

If this method is not implemented in a subclass.

Source code in webtool/auth/manager.py
@abstractmethod
def encode(
    self,
    claims: dict,
    secret_key: str | bytes,
    algorithm: str,
) -> str:
    """
    Encodes the specified claims into a JSON Web Token (JWT).

    Parameters:
        claims: A dictionary containing the claims to be included in the JWT.
        secret_key: The secret key used to sign the JWT.
        algorithm: The signing algorithm to be used for the JWT.

    Returns:
        str: A string representation of the encoded JWT.

    Raises:
         NotImplementedError: If this method is not implemented in a subclass.
    """

    raise NotImplementedError

decode abstractmethod

decode(token, secret_key, algorithm, at_hash=None)

Decodes a JSON Web Token (JWT) and validates its claims.

PARAMETER DESCRIPTION
token

The JWT string to be decoded.

TYPE: str

secret_key

The secret key used to validate the JWT signature.

TYPE: str | bytes

algorithm

The signing algorithm used to verify the JWT,

TYPE: str

at_hash

Optional parameter for additional handling of access tokens.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
dicy

A dictionary containing the claims if the token is valid, or None if the token is invalid or expired.

TYPE: dict | None

RAISES DESCRIPTION
NotImplementedError

If this method is not implemented in a subclass.

Source code in webtool/auth/manager.py
@abstractmethod
def decode(
    self,
    token: str,
    secret_key: str | bytes,
    algorithm: str,
    at_hash: Optional[str] = None,
) -> dict | None:
    """
    Decodes a JSON Web Token (JWT) and validates its claims.

    Parameters:
        token: The JWT string to be decoded.
        secret_key: The secret key used to validate the JWT signature.
        algorithm: The signing algorithm used to verify the JWT,
        at_hash: Optional parameter for additional handling of access tokens.

    Returns:
        dicy: A dictionary containing the claims if the token is valid, or None if the token is invalid or expired.

    Raises:
         NotImplementedError: If this method is not implemented in a subclass.
    """

    raise NotImplementedError

JWTManager

JWTManager(options=None)

Bases: BaseJWTManager

JWT manager for encoding and decoding JSON Web Tokens.

Source code in webtool/auth/manager.py
def __init__(self, options: dict[str, bool | list[str]] | None = None):
    self.jwt = pyjwt.PyJWT(options or self._get_default_options())

jwt instance-attribute

jwt = PyJWT(options or _get_default_options())

encode

encode(claims, secret_key, algorithm)

Encodes the specified claims into a JSON Web Token (JWT) with a specified expiration time.

PARAMETER DESCRIPTION
claims

A dictionary containing the claims to be included in the JWT.

TYPE: dict

secret_key

The secret key used to sign the JWT.

TYPE: str | bytes

algorithm

The signing algorithm to use for the JWT, defaults to 'ES384'.

TYPE: str

RETURNS DESCRIPTION
str

Json Web Token (JWT).

TYPE: str

Source code in webtool/auth/manager.py
def encode(
    self,
    claims: dict,
    secret_key: str | bytes,
    algorithm: str,
) -> str:
    """
    Encodes the specified claims into a JSON Web Token (JWT) with a specified expiration time.

    Parameters:
        claims: A dictionary containing the claims to be included in the JWT.
        secret_key: The secret key used to sign the JWT.
        algorithm: The signing algorithm to use for the JWT, defaults to 'ES384'.

    Returns:
        str: Json Web Token (JWT).
    """

    return self.jwt.encode(claims, secret_key, algorithm)

decode

decode(
    token,
    secret_key,
    algorithm,
    at_hash=None,
    raise_error=False,
    options=None,
)

Decodes a JSON Web Token (JWT) and returns the claims if valid.

PARAMETER DESCRIPTION
token

The JWT string to be decoded.

TYPE: str

secret_key

The secret key used to validate the JWT signature.

TYPE: str | bytes

algorithm

The signing algorithm used for verification JWT, defaults to 'ES384'.

TYPE: str

at_hash

Optional parameter for additional handling of access tokens.

TYPE: Optional[str] DEFAULT: None

raise_error

Optional parameter for additional handling of error messages.

TYPE: bool DEFAULT: False

options

Optional parameters for additional handling of additional errors.

TYPE: dict[str, bool | list[str]] | None DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the claims if the token is valid, or None if the token is invalid or expired.

TYPE: dict | None

Source code in webtool/auth/manager.py
def decode(
    self,
    token: str,
    secret_key: str | bytes,
    algorithm: str,
    at_hash: Optional[str] = None,
    raise_error: bool = False,
    options: dict[str, bool | list[str]] | None = None,
) -> dict | None:
    """
    Decodes a JSON Web Token (JWT) and returns the claims if valid.

    Parameters:
        token: The JWT string to be decoded.
        secret_key: The secret key used to validate the JWT signature.
        algorithm: The signing algorithm used for verification JWT, defaults to 'ES384'.
        at_hash: Optional parameter for additional handling of access tokens.
        raise_error: Optional parameter for additional handling of error messages.
        options: Optional parameters for additional handling of additional errors.

    Returns:
        dict: A dictionary containing the claims if the token is valid, or None if the token is invalid or expired.
    """

    try:
        res = self.jwt.decode(token, secret_key, algorithms=[algorithm], options=options)

        if at_hash and res.get("at_hash") != at_hash:
            raise ValueError("Invalid token")

        return res

    except pyjwt.InvalidTokenError as e:
        if raise_error:
            raise e
        else:
            return None
    except ValueError as e:
        if raise_error:
            raise e
        else:
            return None