Skip to main content

Keycloak authentication for python projects

Project description

sag_py_auth

Maintainability Coverage Status Known Vulnerabilities

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:

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sag-py-auth-0.1.5.tar.gz (13.0 kB view details)

Uploaded Source

Built Distribution

sag_py_auth-0.1.5-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file sag-py-auth-0.1.5.tar.gz.

File metadata

  • Download URL: sag-py-auth-0.1.5.tar.gz
  • Upload date:
  • Size: 13.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.3

File hashes

Hashes for sag-py-auth-0.1.5.tar.gz
Algorithm Hash digest
SHA256 3d3505e3153225e2b063abc459736fa0e61a8800432bc00359e6eb84a335b46b
MD5 e5ef3222723da8dd142a97af79df5586
BLAKE2b-256 e9935cc1cc1ade3dbd5b0c787fb6afb93a0ce823b74699e7240673ef5890a4c1

See more details on using hashes here.

File details

Details for the file sag_py_auth-0.1.5-py3-none-any.whl.

File metadata

  • Download URL: sag_py_auth-0.1.5-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.3

File hashes

Hashes for sag_py_auth-0.1.5-py3-none-any.whl
Algorithm Hash digest
SHA256 b451563a1bc05b027caff5428db99ab0825c4e0f315868c48c04700a5c6484cf
MD5 0f5602465c6efac6e2145f1a82d402e4
BLAKE2b-256 4ccba86416093cd7549c4c3d820ea3f1c84c32f4fb21dc5f766d01b1c48371bd

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page