Authentication in Panther#
Authentication in Panther ensures that only authorized users can access your APIs and WebSocket connections. You can configure which authentication class to use in your configs.
How Authentication Works#
- The
authparameter for an API or WebSocket should be an async function or a class with an async__call__method. Panther will use this callable to verify the user. - If you do not set
auth, Panther will use the defaultAUTHENTICATIONfrom your config when it is configured. - Built-in JWT authentication classes return
Nonewhen their expected token source is absent, sorequest.usercan beNone; use permissions when an endpoint requires an authenticated user. - If authentication fails, Panther raises
HTTP_401_UNAUTHORIZED. - The authenticated user is available as:
request.userin API viewsself.userin WebSocket connections
Note: With built-in JWT authentication, missing credentials leave
request.userasNone. Use permissions such asIsAuthenticatedwhen an endpoint must require a user.
Built-in Authentication Classes#
Panther provides three built-in authentication classes, all based on JWT (JSON Web Token):
1. JWT Authentication#
- Retrieves the JWT token from the
Authorizationheader in the request. - Expects the header format:
Authorization: Bearer <token> - Decodes the token, validates it, and fetches the corresponding user.
- By default, uses
panther.db.models.BaseUseras the user model unless you setUSER_MODELin your configs. - Handles token revocation if Redis is connected (for logout and refresh scenarios).
Example usage#
AUTHENTICATION = 'panther.authentications.JWTAuthentication'
JWT Configuration#
You can customize JWT behavior by setting JWT_CONFIG in your configs. Example:
| core/configs.py | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
2. QueryParam JWT Authentication#
- Works like
JWTAuthentication, but expects the token in the query parameters instead of headers. - Useful for WebSocket authentication or scenarios where headers are not available.
- Pass the token as a query parameter:
- Example:
https://example.com?authorization=<jwt_token>
Example usage#
AUTHENTICATION = 'panther.authentications.QueryParamJWTAuthentication'
3. Cookie JWT Authentication#
- Works like
JWTAuthentication, but expects the token in cookies. - Looks for
access_tokenin cookies for authentication. - Optionally, can use
refresh_tokenin cookies for token refresh. - Pass the token in cookies:
- Example:
Cookies: access_token=<jwt_token>
Example usage#
AUTHENTICATION = 'panther.authentications.CookieJWTAuthentication'
WebSocket Authentication#
For WebSocket connections, it is recommended to use QueryParamJWTAuthentication since headers are not always available. To enable this, set the following in your configs:
WS_AUTHENTICATION = 'panther.authentications.QueryParamJWTAuthentication'
Custom Authentication#
You can implement your own authentication logic by either:
- Inheriting from panther.authentications.BaseAuthentication and implementing an async __call__ method (recommended for consistency), or
- Providing any async function or class with an async __call__ method.
Steps to create a custom authentication class:#
- Inherit from
BaseAuthenticationand implement async__call__Or as a function or plain class:from panther.request import Request from panther.exceptions import AuthenticationAPIError from panther.authentications import BaseAuthentication class CustomAuthentication(BaseAuthentication): async def __call__(self, request: Request): # Your authentication logic here # Return an instance of USER_MODEL (default: BaseUser) # Or raise AuthenticationAPIError on failure ...async def custom_authentication(request: Request): # Your authentication logic here # Return an instance of USER_MODEL (default: BaseUser) # Or raise AuthenticationAPIError on failure ... - Configure your custom authentication class or function in your configs (if you want it as default):
AUTHENTICATION = 'project_name.core.authentications.CustomAuthentication' - Or set it per API using the
authparameter:@API(auth=CustomAuthentication) async def my_api(request: Request): ...
Error Handling#
- If authentication fails, raise
panther.exceptions.AuthenticationAPIErrorwith an appropriate message. - Panther will automatically handle and return a 401 Unauthorized response.
Summary#
- Choose and configure the appropriate authentication class or function for your use case.
- Use JWT configuration options to control token behavior.
- For WebSocket, prefer query parameter-based authentication.
- Implement custom authentication as an async function or a class with an async
__call__method. - With built-in JWT authentication, missing credentials leave
request.userasNone; use permissions to require authenticated access.