sag_py_auth
This provides a way to secure your fastapi with keycloak jwt bearer authentication.
What it does
- Secure your api endpoints
- Verifies auth tokens: signature, expiration, issuer, audience
- Allows to set permissions by specifying roles and realm roles
How to use
Installation
pip install sag-py-auth
Secure your apis
First create the fast api dependency with the auth config:
from sag_py_auth.models import AuthConfig, TokenRole
from sag_py_auth.jwt_auth import JwtAuth
from fastapi import Depends
auth_config = AuthConfig("https://authserver.com/auth/realms/projectName", "myaudience")
required_roles = [TokenRole("clientname", "adminrole")]
required_realm_roles = ["additionalrealmrole"]
requires_admin = Depends(JwtAuth(auth_config, required_roles, required_realm_roles))
Afterwards you can use it in your route like that:
@app.post("/posts", dependencies=[requires_admin], tags=["posts"])
async def add_post(post: PostSchema) -> dict:
Or if you use sub routes, auth can also be enforced for the entire route like that:
router = APIRouter()
router.include_router(sub_router, tags=["my_api_tag"], prefix="/subroute",dependencies=[requires_admin])
Get user information
The Jwt call directly returns a token object that can be used to get additional information.
Furthermore you can access the context directly:
from sag_py_auth.auth_context import get_token as get_token_from_context
token = get_token_from_context()
This works in async calls but not in sub threads (without additional changes).
See:
- https://docs.python.org/3/library/contextvars.html
- https://kobybass.medium.com/python-contextvars-and-multithreading-faa33dbe953d
Methods available on the token object
- get_field_value: to get the value of a claim field (or an empty string if not present)
- get_roles: Gets the roles of a specific client
- has_role: Verify if a spcific client has a role
- get_realm_roles: Get the realm roles
- has_realm_role: Check if the user has a specific realm role
Log user data
It is possible to log the preferred_username and the azp value (party that created the token) of the token by adding a filter.
import logging
from sag_py_auth import UserNameLoggingFilter
console_handler = logging.StreamHandler(sys.stdout)
console_handler.addFilter(UserNameLoggingFilter())
The filter provides the following two fields as soon as the user is authenticated: user_name, authorized_party
How a token has to look like
{
"iss": "https://authserver.com/auth/realms/projectName",
"aud": ["audienceOne", "audienceTwo"],
"typ": "Bearer",
"azp": "public-project-swagger",
"preferred_username": "preferredUsernameValue",
.....
"realm_access": {
"roles": ["myRealmRoleOne"]
},
"resource_access": {
"my-client-one": {
"roles": ["a-permission-role", "user"]
},
"my-client-two": {
"roles": ["a-permission-role", "admin"]
}
}
}
- realm_access contains the realm roles
- resource_access contains the token roles for one or multiple clients
How to start developing
With vscode
Just install vscode with dev containers extension. All required extensions and configurations are prepared automatically.
With pycharm
- Install latest pycharm
- Install pycharm plugin BlackConnect
- Install pycharm plugin Mypy
- Configure the python interpreter/venv
- pip install requirements-dev.txt
- pip install black[d]
- Ctl+Alt+S => Check Tools => BlackConnect => Trigger when saving changed files
- Ctl+Alt+S => Check Tools => BlackConnect => Trigger on code reformat
- Ctl+Alt+S => Click Tools => BlackConnect => "Load from pyproject.yaml" (ensure line length is 120)
- Ctl+Alt+S => Click Tools => BlackConnect => Configure path to the blackd.exe at the "local instance" config (e.g. C:\Python310\Scripts\blackd.exe)
- Ctl+Alt+S => Click Tools => Actions on save => Reformat code
- Restart pycharm
How to publish
- Update the version in setup.py and commit your change
- Create a tag with the same version number
- Let github do the rest
Metadata
Release files for sag-py-auth 1.2.5
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sag_py_auth-1.2.5.tar.gz | 14.0 kB | Without provenance | Details for sag_py_auth-1.2.5.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sag_py_auth-1.2.5-py3-none-any.whl | Python 3 | none | any | Details for sag_py_auth-1.2.5-py3-none-any.whl |
Total release size: 22.9 kB
Release files / sag_py_auth-1.2.5.tar.gz
| Download URL | sag_py_auth-1.2.5.tar.gz |
|---|---|
| Size | 14.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7f5b5526623f8e115a140aac9aa62bb2eef1c6672e3813074fc86003a389d84b
|
|
BLAKE2b-256 checksum How to use checksums |
84f6d3f32a3fe4b7805683167760447210291370fbfe4cf951e2cefe25822a93
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Release files / sag_py_auth-1.2.5-py3-none-any.whl
| Download URL | sag_py_auth-1.2.5-py3-none-any.whl |
|---|---|
| Size | 9.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
193f12861b7f326de9278c3b038de5c293615a3357ba90176c4210e5f7b7c438
|
|
BLAKE2b-256 checksum How to use checksums |
b15060555b4f023d455588381d1cd6f28dec109967cad950f9a994bb50e537b6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Security for sag-py-auth 1.2.5
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.