Authx#
authx.main.AuthX #
AuthX(config=AuthXConfig(), model=None, login_type=None)
Bases: _CallbackHandler[T], _ErrorHandler
The base class for AuthX.
AuthX enables JWT management within a FastAPI application. Its main purpose is to provide a reusable & simple syntax to protect API with JSON Web Token authentication.
| PARAMETER | DESCRIPTION |
|---|---|
config | Configuration instance to use. Defaults to AuthXConfig(). TYPE: |
model | Model type hint. Defaults to dict[str, Any]. TYPE: |
Note
AuthX is a Generic python object. Its TypeVar is not mandatory but helps type hinting furing development
AuthX base object.
| PARAMETER | DESCRIPTION |
|---|---|
config | Configuration instance to use. Defaults to AuthXConfig(). TYPE: |
model | Model type hint. Defaults to dict[str, Any]. TYPE: |
login_type | Explicit login type for manager-based auth contexts. TYPE: |
Source code in authx/main.py
config property #
AuthX Configuration getter.
| RETURNS | DESCRIPTION |
|---|---|
AuthXConfig | Configuration BaseSettings TYPE: |
DEPENDENCY property #
FastAPI Dependency to return an AuthX sub-object within the route context.
FRESH_REQUIRED property #
FastAPI Dependency to enforce valid token availability in request.
ACCESS_REQUIRED property #
FastAPI Dependency to enforce presence of an access token in request.
REFRESH_REQUIRED property #
FastAPI Dependency to enforce presence of a refresh token in request.
CURRENT_SUBJECT property #
FastAPI Dependency to retrieve the current subject from request.
WS_AUTH_REQUIRED property #
FastAPI Dependency to enforce valid access token on a WebSocket connection.
Extracts the token from the token query parameter or the Authorization header of the WebSocket handshake request.
fresh_token_required property #
FastAPI Dependency to enforce presence of a fresh access token in request.
access_token_required property #
FastAPI Dependency to enforce presence of an access token in request.
refresh_token_required property #
FastAPI Dependency to enforce presence of a refresh token in request.
MSG_MissingTokenError class-attribute instance-attribute #
MSG_TokenRequiredError class-attribute instance-attribute #
MSG_FreshTokenRequiredError class-attribute instance-attribute #
MSG_AccessTokenRequiredError class-attribute instance-attribute #
MSG_RefreshTokenRequiredError class-attribute instance-attribute #
MSG_CSRFError class-attribute instance-attribute #
MSG_PolicyEvaluationError class-attribute instance-attribute #
load_config #
Load and store the configuration for the authentication system.
Sets the internal configuration object with the provided authentication configuration.
| PARAMETER | DESCRIPTION |
|---|---|
config | The configuration settings for the AuthX authentication system. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
None | None |
Source code in authx/main.py
get_access_token_from_request async #
Dependency to retrieve access token from request.
| PARAMETER | DESCRIPTION |
|---|---|
request | Request to retrieve access token from TYPE: |
locations | Locations to retrieve token from. Defaults to None. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
MissingTokenError | When no |
| RETURNS | DESCRIPTION |
|---|---|
RequestToken | Request Token instance for TYPE: |
Source code in authx/main.py
get_refresh_token_from_request async #
Dependency to retrieve refresh token from request.
| PARAMETER | DESCRIPTION |
|---|---|
request | Request to retrieve refresh token from TYPE: |
locations | Locations to retrieve token from. Defaults to None. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
MissingTokenError | When no |
| RETURNS | DESCRIPTION |
|---|---|
RequestToken | Request Token instance for TYPE: |
Source code in authx/main.py
verify_token #
Verify a request token.
Attempts verification with the current key first, then falls back to the previous key if key rotation is configured.
| PARAMETER | DESCRIPTION |
|---|---|
token | RequestToken instance TYPE: |
verify_type | Apply token type verification. Defaults to True. TYPE: |
verify_fresh | Apply token freshness verification. Defaults to False. TYPE: |
verify_csrf | Apply token CSRF verification. Defaults to True. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenPayload | Verified token payload TYPE: |
Source code in authx/main.py
create_access_token #
create_access_token(uid, fresh=False, headers=None, expiry=None, data=None, audience=None, scopes=None, *args, **kwargs)
Generate an Access Token.
| PARAMETER | DESCRIPTION |
|---|---|
uid | Unique identifier to generate token for TYPE: |
fresh | Generate fresh token. Defaults to False. TYPE: |
headers | Custom JWT headers. Defaults to None. TYPE: |
expiry | Use a user defined expiry claim. Defaults to None. TYPE: |
data | Additional data to store in token. Defaults to None. TYPE: |
audience | Audience claim. Defaults to None. TYPE: |
scopes | List of scopes to include in the token. Defaults to None. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | Access Token TYPE: |
Example
Source code in authx/main.py
create_refresh_token #
create_refresh_token(uid, headers=None, expiry=None, data=None, audience=None, scopes=None, *args, **kwargs)
Generate a Refresh Token.
| PARAMETER | DESCRIPTION |
|---|---|
uid | Unique identifier to generate token for TYPE: |
headers | Custom JWT headers. Defaults to None. TYPE: |
expiry | Use a user defined expiry claim. Defaults to None. TYPE: |
data | Additional data to store in token. Defaults to None. TYPE: |
audience | Audience claim. Defaults to None. TYPE: |
scopes | List of scopes to include in the token. Defaults to None. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | Refresh Token TYPE: |
Source code in authx/main.py
create_token_pair #
create_token_pair(uid, fresh=False, headers=None, access_expiry=None, refresh_expiry=None, data=None, audience=None, access_scopes=None, refresh_scopes=None)
Generate an access and refresh token pair.
Convenience method that creates both tokens at once and returns them in a standardized TokenResponse model.
| PARAMETER | DESCRIPTION |
|---|---|
uid | Unique identifier of the user. TYPE: |
fresh | Whether the access token should be marked as fresh. Defaults to False. TYPE: |
headers | Optional custom JWT headers applied to both tokens. TYPE: |
access_expiry | Optional expiry override for the access token. TYPE: |
refresh_expiry | Optional expiry override for the refresh token. TYPE: |
data | Optional additional data stored in both tokens. TYPE: |
audience | Optional audience claim for both tokens. TYPE: |
access_scopes | Optional scopes for the access token. TYPE: |
refresh_scopes | Optional scopes for the refresh token. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenResponse | A model containing TYPE: |
Example
Source code in authx/main.py
set_access_cookies #
Add 'Set-Cookie' for access token in response header.
| PARAMETER | DESCRIPTION |
|---|---|
token | Access token TYPE: |
response | response to set cookie on TYPE: |
max_age | Max Age cookie parameter. Defaults to None. TYPE: |
Source code in authx/main.py
set_refresh_cookies #
Add 'Set-Cookie' for refresh token in response header.
| PARAMETER | DESCRIPTION |
|---|---|
token | Refresh token TYPE: |
response | response to set cookie on TYPE: |
max_age | Max Age cookie parameter. Defaults to None. TYPE: |
Source code in authx/main.py
unset_access_cookies #
Remove 'Set-Cookie' for access token in response header.
| PARAMETER | DESCRIPTION |
|---|---|
response | response to remove cooke from TYPE: |
Source code in authx/main.py
unset_refresh_cookies #
Remove 'Set-Cookie' for refresh token in response header.
| PARAMETER | DESCRIPTION |
|---|---|
response | response to remove cooke from TYPE: |
Source code in authx/main.py
unset_cookies #
Remove 'Set-Cookie' for tokens from response headers.
| PARAMETER | DESCRIPTION |
|---|---|
response | response to remove token cookies from TYPE: |
Source code in authx/main.py
get_dependency #
FastAPI Dependency to return a AuthX sub-object within the route context.
| PARAMETER | DESCRIPTION |
|---|---|
request | Request context managed by FastAPI TYPE: |
response | Response context managed by FastAPI TYPE: |
Note
The AuthXDeps is a utility class, to enable quick token operations within the route logic. It provides methods to avoid additional code in your route that would be outside of the route logic
Such methods includes setting and unsetting cookies without the need to generate a response object beforehand
| RETURNS | DESCRIPTION |
|---|---|
AuthXDeps | The contextful AuthX object TYPE: |
Source code in authx/main.py
token_required #
token_required(type='access', verify_type=True, verify_fresh=False, verify_csrf=None, locations=None)
Dependency to enforce valid token availability in request.
| PARAMETER | DESCRIPTION |
|---|---|
type | Require a given token type. Defaults to "access". TYPE: |
verify_type | Apply type verification. Defaults to True. TYPE: |
verify_fresh | Require token freshness. Defaults to False. TYPE: |
verify_csrf | Enable CSRF verification. Defaults to None. TYPE: |
locations | Locations to retrieve token from. Defaults to None. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[TokenPayload]] | Callable[[Request], TokenPayload]: Dependency for Valid token Payload retrieval |
Source code in authx/main.py
scopes_required #
scopes_required(*scopes, all_required=True, verify_type=True, verify_fresh=False, verify_csrf=None, locations=None)
Dependency to enforce required scopes in token.
Creates a FastAPI dependency that validates that the token contains the required scopes. Supports both simple and hierarchical scopes with wildcard matching (e.g., "admin:*" matches "admin:users").
| PARAMETER | DESCRIPTION |
|---|---|
*scopes | Variable number of scope strings required. TYPE: |
all_required | If True (default), ALL scopes must be present (AND logic). If False, at least ONE scope must be present (OR logic). TYPE: |
verify_type | Apply token type verification. Defaults to True. TYPE: |
verify_fresh | Require token freshness. Defaults to False. TYPE: |
verify_csrf | Enable CSRF verification. Defaults to None (uses config). TYPE: |
locations | Locations to retrieve token from. Defaults to None. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[TokenPayload]] | Callable[[Request], Awaitable[TokenPayload]]: Dependency for scope validation. |
| RAISES | DESCRIPTION |
|---|---|
InsufficientScopeError | When token lacks required scopes. |
Example
# Require single scope
@app.get("/users", dependencies=[Depends(auth.scopes_required("users:read"))])
async def list_users(): ...
# Require multiple scopes (AND)
@app.delete("/users/{id}", dependencies=[Depends(auth.scopes_required("users:read", "users:delete"))])
async def delete_user(id: int): ...
# Require any of the scopes (OR)
@app.get("/admin", dependencies=[Depends(auth.scopes_required("admin", "superuser", all_required=False))])
async def admin_panel(): ...
# Wildcard scope
@app.get("/admin/users", dependencies=[Depends(auth.scopes_required("admin:*"))])
async def admin_users(): ...
Source code in authx/main.py
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | |
get_current_subject async #
Retrieve the currently authenticated subject from the request.
Validates the request token and fetches the corresponding subject based on the user identifier.
| PARAMETER | DESCRIPTION |
|---|---|
request | The HTTP request containing authentication credentials. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Optional[T] | The authenticated subject if present, otherwise None. |
Source code in authx/main.py
get_token_from_request async #
get_token_from_request(request: Request, type: TokenType = 'access', optional: Literal[True] = True, locations: Optional[TokenLocations] = None) -> Optional[RequestToken]
get_token_from_request(request: Request, type: TokenType = 'access', optional: Literal[False] = False, locations: Optional[TokenLocations] = None) -> RequestToken
Retrieve token from request.
| PARAMETER | DESCRIPTION |
|---|---|
request | The FastAPI request object. TYPE: |
type | The type of token to retrieve from request. Defaults to "access". TYPE: |
optional | Whether or not to enforce token presence in request. Defaults to True. TYPE: |
locations | Locations to retrieve token from. Defaults to None (uses configured JWT_TOKEN_LOCATION). TYPE: |
Note
When optional=True, the return value might be None if no token is available in request.
When optional=False, raises a MissingTokenError.
| RETURNS | DESCRIPTION |
|---|---|
Optional[RequestToken] | Optional[RequestToken]: The RequestToken if available, None if optional and not found. |
Example
Source code in authx/main.py
implicit_refresh_middleware async #
FastAPI Middleware to enable token refresh for an APIRouter.
| PARAMETER | DESCRIPTION |
|---|---|
request | Incoming request TYPE: |
call_next | Endpoint logic to be called TYPE: |
Note
This middleware is only based on access tokens. Using implicit refresh mechanism makes use of refresh tokens unnecessary.
Note
The refreshed access token will not be considered as fresh
Note
The implicit refresh mechanism is only enabled for authorization through cookies.
| RETURNS | DESCRIPTION |
|---|---|
Response | Response with update access token cookie if relevant TYPE: |
Source code in authx/main.py
rate_limited #
Dependency combining rate limiting with access token verification.
| PARAMETER | DESCRIPTION |
|---|---|
max_requests | Maximum requests allowed within the window. TYPE: |
window | Time window in seconds. TYPE: |
key_func | Callable to extract rate limit key from request. Defaults to client IP. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Request], Awaitable[TokenPayload]] | A FastAPI dependency that enforces both rate limiting and token auth. |
Example
Source code in authx/main.py
set_session_store #
Register a session storage backend.
| PARAMETER | DESCRIPTION |
|---|---|
store | An object implementing the TYPE: |
create_session async #
Create a new session and persist it via the session store.
| PARAMETER | DESCRIPTION |
|---|---|
uid | User identifier. TYPE: |
request | Optional HTTP request for IP/User-Agent extraction. TYPE: |
device_info | Optional additional device metadata. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
SessionInfo | The created |
Source code in authx/main.py
list_sessions async #
List all active sessions for a user.
| PARAMETER | DESCRIPTION |
|---|---|
uid | User identifier. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[SessionInfo] | List of active |
Source code in authx/main.py
revoke_session async #
Revoke a single session by ID.
| PARAMETER | DESCRIPTION |
|---|---|
session_id | The session to revoke. TYPE: |
revoke_all_sessions async #
Revoke all sessions for a user.
| PARAMETER | DESCRIPTION |
|---|---|
uid | User identifier. TYPE: |
get_session async #
Retrieve a session by ID.
| PARAMETER | DESCRIPTION |
|---|---|
session_id | The session to look up. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Optional[SessionInfo] | The |
Source code in authx/main.py
ensure_request_exception_handlers #
Install default AuthX handlers for the active request if the app has none.
FastAPI exception handlers are normally registered with handle_errors(app). Minimal apps that omit it should still return HTTP auth errors instead of leaking AuthX exceptions as 500 responses.
Source code in authx/_internal/_error.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 | |
handle_errors #
Add the FastAPI.exception_handlers relative to AuthX exceptions.
| PARAMETER | DESCRIPTION |
|---|---|
app | the FastAPI application to handle errors for TYPE: |
Source code in authx/_internal/_error.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
set_callback_get_model_instance #
set_callback_token_blocklist #
set_subject_getter #
Set the callback to run for subject retrieval and serialization.
set_token_blocklist #
is_token_in_blocklist async #
Check if token is in blocklist.