Skip to content

Jwtlib

jwtlib

jwtlib: A framework-agnostic JWT authentication library.


Summary

jwtlib provides a set of pure logic components for handling JWT discovery, user registration, login, and token introspection. It is designed to be decoupled from any specific web framework (like FastAPI or Flask).


Installation

Install using pip:

1
pip install py-jwt

Quick Start

1
2
3
4
5
6
7
import asyncio
from jwtlib import login_user, LoginRequest

async def main():
    request = LoginRequest(username="admin", password="password")
    response = await login_user(request)
    print(f"Access Token: {response.access_token}")

Public API

This package re-exports the core authentication primitives. Consumers are encouraged to import from this namespace for high-level operations.

Authentication: - register_user - login_user - logout_user - get_logged_in_user

Introspection: - introspect_token - authenticate_request (logic-only)

Models: - RegisterRequest / LoginRequest / LoginResponse / LogoutResponse - PublicUser - IntrospectRequest / IntrospectResponse - TokenPayload

Exceptions: - AuthError - InvalidToken - UserNotFound


Classes

AuthError

Bases: Exception

Base authentication and authorization error.

Notes

Guarantees:

1
2
- All authentication-related exceptions raised by this library inherit from this class
- Consumers may catch this exception to handle all auth failures uniformly

IntrospectRequest

Bases: BaseModel

Payload for requesting token introspection.

Attributes:

Name Type Description
token str

JWT access token to introspect.

IntrospectResponse

Bases: BaseModel

Result of a token introspection operation.

Attributes:

Name Type Description
active bool

Indicates whether the token is valid and active.

user Optional[PublicUser]

Public user details if the token is valid; otherwise null.

InvalidToken

Bases: AuthError

Raised when a JWT is missing, malformed, expired, or invalid.

Notes

Guarantees:

1
- This error indicates that the provided token cannot be used to authenticate a request

LoginRequest

Bases: IdentityMixin, PasswordMixin

Payload for authenticating a user and issuing a JWT.

Attributes:

Name Type Description
username str

Username identifier.

password str

Plain-text password to be verified.

LoginResponse

Bases: BaseModel

Response returned after successful authentication.

Attributes:

Name Type Description
access_token str

JWT access token for authenticated requests.

user PublicUser

Public profile of the authenticated user.

LogoutResponse

Bases: BaseModel

Response returned after a logout operation.

Attributes:

Name Type Description
message str

Human-readable logout confirmation.

PublicUser

Bases: IdentityMixin, ActiveStateMixin

Public-facing user representation returned by authentication APIs.

Attributes:

Name Type Description
username str

Unique username identifier.

email EmailStr

User's email address.

is_active bool

Whether the user account is active.

RegisterRequest

Bases: IdentityMixin, PasswordMixin

Payload for registering a new user account.

Attributes:

Name Type Description
username str

Unique username identifier.

email EmailStr

User's email address.

password str

Plain-text password (to be hashed by the repository layer).

TokenPayload

Bases: BaseModel

Decoded JWT payload.

Attributes:

Name Type Description
sub str

Subject claim identifying the user (typically a username or user ID).

exp int

Expiration time as a Unix timestamp (seconds since epoch).

Notes

Responsibilities:

1
- Represents the validated claims extracted from a JWT after signature verification. This model is used internally to enforce required claims and provide a typed interface to token data.

Guarantees:

1
- This model assumes the JWT signature has already been verified. No authorization decisions should be made solely on this model. Additional claims may exist but are intentionally ignored.

User

Bases: BaseDocument, IdentityMixin, ActiveStateMixin

Internal user persistence model.

Attributes:

Name Type Description
hashed_password str

Secure hash of the user's password.

Notes

Responsibilities:

1
- Represents a user record as stored in the database. Includes sensitive fields and is strictly confined to the persistence layer.

Guarantees:

1
- This model MUST NOT be returned from authentication APIs. Consumers should use `PublicUser` instead. Password verification is handled by the repository layer.

UserNotFound

Bases: AuthError

Raised when a valid token does not map to an existing user.

Notes

Guarantees:

1
- Indicates that authentication succeeded at the token level, but the associated user record could not be resolved

Functions

authenticate_request async

authenticate_request(should_skip_authentication: Callable[[str, str], bool], *, method: str, path: str, authorization_token: Optional[str]) -> Optional[PublicUser]

Authenticate an incoming request using token introspection.

Parameters:

Name Type Description Default
should_skip_authentication Callable[[str, str], bool]

Callable that decides whether authentication is required for a given HTTP method and path.

required
method str

HTTP method of the incoming request.

required
path str

Request path.

required
authorization_token str | None

JWT access token provided by the caller.

required

Returns:

Type Description
Optional[PublicUser]

PublicUser | None: PublicUser if authentication succeeds; None if authentication is skipped.

Raises:

Type Description
InvalidToken

If authentication is required but the token is missing, invalid, or revoked.

AuthServiceUnavailable

If the auth service cannot be reached.

Notes

Responsibilities:

1
- Determines whether authentication should be skipped for the given request context and, if not, resolves the authenticated user via token introspection

Guarantees:

1
- This function does not parse Authorization headers; callers must supply the raw token. Access-control policy is externalized via `should_skip_authentication`.

get_logged_in_user async

get_logged_in_user(token: str, repo: Optional[UserRepository] = None) -> PublicUser

Resolve the currently authenticated user from a JWT.

Parameters:

Name Type Description Default
token str

JWT access token.

required
repo UserRepository

Optional user repository instance. If not provided, a default repository is obtained via dependency utilities.

None

Returns:

Name Type Description
PublicUser PublicUser

The authenticated user as a PublicUser.

Raises:

Type Description
InvalidToken

If the token is missing, malformed, or invalid.

AuthError

If the token is valid, but the user cannot be resolved.

introspect_token async

introspect_token(token: str, repo: Optional[UserRepository] = None) -> IntrospectResponse

Introspect a JWT for service-to-service authentication.

Parameters:

Name Type Description Default
token str

JWT access token to introspect.

required
repo UserRepository

Optional user repository instance. If not provided, a default repository is obtained via dependency utilities.

None

Returns:

Name Type Description
IntrospectResponse IntrospectResponse

IntrospectResponse indicating valid token with user, invalid token, or valid token with no user.

Notes

Responsibilities:

1
- Validates the provided token and resolves the associated user, returning a structured introspection response suitable for internal service use

Guarantees:

1
- This function never raises authentication exceptions. Instead, it returns a typed response indicating token validity and user presence.

login_user async

login_user(user: LoginRequest, repo: Optional[UserRepository] = None) -> LoginResponse

Authenticate a user and issue an access token.

Parameters:

Name Type Description Default
user LoginRequest

Login payload containing username and password.

required
repo UserRepository

Optional user repository instance. If not provided, a default repository is obtained via dependency utilities.

None

Returns:

Name Type Description
LoginResponse LoginResponse

LoginResponse containing the issued access token and related metadata.

Raises:

Type Description
AuthError

If the credentials are invalid.

logout_user async

logout_user() -> LogoutResponse

Perform a stateless logout.

Returns:

Name Type Description
LogoutResponse LogoutResponse

LogoutResponse containing a logout confirmation message.

Notes

Guarantees:

1
- This function does not invalidate tokens server-side. Instead, it provides a standardized response indicating that the client must discard its token.

register_user async

register_user(user: RegisterRequest, repo: Optional[UserRepository] = None) -> PublicUser

Register a new user.

Parameters:

Name Type Description Default
user RegisterRequest

Registration payload containing username, email, and password.

required
repo UserRepository

Optional user repository instance. If not provided, a default repository is obtained via dependency utilities.

None

Returns:

Name Type Description
PublicUser PublicUser

The newly created user as a public user representation.