Skip to main content

Keycloak brand/instance authentication for python projects

Project description

sag_py_auth_brand

Maintainability Coverage Status Known Vulnerabilities

This provides a way to secure your fastapi with keycloak jwt bearer authentication. This library bases on sag_py_auth and adds support for instances/brands.

What it does

  • Secure your api endpoints
  • Verifies auth tokens: signature, expiration, issuer, audience
  • Verifies the brand/customer over a token role (+ alias support)
  • Verifies the instance over a token role
  • Verifies the stage over a realm role
  • Allows to set additional permissions by specifying further token roles
  • Supplies brand information from context

How to use

Installation

pip install sag-py-auth-brand

Secure your apis

First create the fast api dependency with the auth config:

from sag_py_auth import TokenRole
from sag_py_auth_brand.models import AuthConfig
from sag_py_auth_brand.brand_jwt_auth import BrandJwtAuth
from fastapi import Depends

auth_config = BrandAuthConfig("https://authserver.com/auth/realms/projectName", "myaudience", "myinstance", "mystage")
required_roles = [TokenRole("clientname", "adminrole")]
requires_admin = Depends(BrandJwtAuth(auth_config, required_endpoint_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 brand information

See sag_py_auth to find out how to access the token and user info.

Furthermore you can get the brand by accessing it over the context:

from sag_py_auth_brand.request_brand_context import get_brand as get_brand_from_context
brand = get_brand_from_context()

This works in async calls but not in sub threads (without additional changes).

See:

Log the brand

It is possible to log the brand by adding a filter.

import logging
from sag_py_auth_brand.request_brand_logging_filter import RequestBrandLoggingFilter

console_handler = logging.StreamHandler(sys.stdout)
console_handler.addFilter(RequestBrandLoggingFilter())

The filter provides the field request_brand and request_brand_alias with the brand.

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": ["myStage"]
    },
    "resource_access": {
        "role-instance": {
            "roles": ["myInstance"]
        },
        "role-brand": {
            "roles": ["myBrand"]
        },
        "role-endpoint": {
            "roles": ["permissionOne", "permissionTwo"]
        },
        "role-brand-alias": {
            "roles": ["myBrand", "myBrandAliasOne", "myBrandAliasTwo"]
        }
    }
}
  • role-endpoint is just required for permission checks of the api endpoint
  • role-brand-alias is optional for the alias feature. If you don't use aliases it can be left ayway.
  • role-brand-alias must contain exactly one original brand (also called the compound brand alias) together with one or multiple aliases

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-brand-0.2.1.tar.gz (9.3 kB view details)

Uploaded Source

Built Distribution

sag_py_auth_brand-0.2.1-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file sag-py-auth-brand-0.2.1.tar.gz.

File metadata

  • Download URL: sag-py-auth-brand-0.2.1.tar.gz
  • Upload date:
  • Size: 9.3 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-brand-0.2.1.tar.gz
Algorithm Hash digest
SHA256 9cdbb78234531595bb477ccfedd32dd811765fedfc80277e10fc8ce30e454f23
MD5 1af730d31021a3640f9203b9b2518183
BLAKE2b-256 63a6b17c7e26f74725c6a8ac468728cff6774e97864b29282e9494cc662f2412

See more details on using hashes here.

File details

Details for the file sag_py_auth_brand-0.2.1-py3-none-any.whl.

File metadata

File hashes

Hashes for sag_py_auth_brand-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 793537d4bb696e652aa8bb07e09810897edd3a2063a5b8ee45e84e004040c4dc
MD5 352208654f1f66f62b2cd1e2a907703e
BLAKE2b-256 59307d2a78c8f2b233a59346bf8e9af56ad82199d71a5c3e53edb5c762877a6e

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