Skip to main content

OICD

oidc

version: 0.1.0

This package is designed for use in your application with OIDC.

Features

  • feature

Install

pip install oidc

Use examples

API для OICD на библиотеки Sanic

Как пользоваться библиотекой OICD : Изначально нам необходим редирект на Keycloak

Например, в Sanic мы создаем объект: Передаем url БД redis и имя Realm

app.ctx.oidc_client = CreateOIDCClient(config["REDIS_URL"],
                           config['KEYCLOAK_REALM_NAME'])

Теперь получаем редирект передаем конфиг: config:dict там переменные окружения передаем с .env

app.ctx.redirect_uri = app.ctx.oidc_client.get_redirect_uri(config)

Пример:

# Открываем соединение с Redis при старте
@api.before_server_start
async def setup_redis(app, _):
    # Подключаем Redis
    app.ctx.redis = redis.from_url(
        config["REDIS_URL"],
        decode_responses=True
    )

    # Создаём OIDC + PKCE менеджеры на основе redis URL
    createOIDCClient = CreateOIDCClient(config, app.ctx.redis)
    app.ctx.oidc_client = createOIDCClient

# например на маршрут /login
@api.get("/login")
async def auth_login(request):
    return response.redirect(request.app.ctx.redirect_uri)

Нас перебрасывает на сервис Keycloak

Авторизируемся

После успешной авторизации мы пропускаем в наше приложение:

@api.get("/callback")
async def auth_callback(request: Request):
    # Достаем код и state
    
    code = request.args.get("code")
    state = request.args.get("state")

    if not code or not state:
        return response.json({"error": "Missing code or state"}, status=400)

    code_verifier = await request.app.ctx.oidc_client.pkce.pop(state)
    
    if not code_verifier:
        return response.json({"error": "Invalid/expired state"}, status=400)

    try:
        tokens = await request.app.ctx.oidc_client.exchange_code(code, code_verifier)
    except Exception as e:
        return response.json(
            {"error": "Token exchange failed", "details": str(e)},
            status=400
        )

    claims = await request.app.ctx.oidc_client.oidc.verify_token(tokens["access_token"])

    await request.app.ctx.oidc_client.save_session(claims["sub"], tokens, claims)

    return response.json({"message": "ok", "user": claims})

Для проверки токена и пользователя, мы используем middleware

Пример:

@api.middleware("request")
async def keycloak_middleware(request: Request):
    auth = request.headers.get("Authorization")
    if not auth:
        request.ctx.user = None
        logger.info(f"User is : {request.ctx.user}")
        return

    token = auth.replace("Bearer ", "")
    request.ctx.user = await (request.app.ctx.oidc_client.get_user_from_token(token))
    

Roadmap

  • 0.1.0 init

Develop

install

how to install for develop

structure modules

add feature

publish

Metadata

Release files for oidc-python 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for oidc-python 0.1.0
File Size Uploaded Provenance Actions
oidc_python-0.1.0.tar.gz 7.1 kB Without provenance Details for oidc_python-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for oidc-python 0.1.0
File Interpreter ABI Platform Actions
oidc_python-0.1.0-py3-none-any.whl Python 3 none any Details for oidc_python-0.1.0-py3-none-any.whl

Total release size: 16.6 kB

Release files / oidc_python-0.1.0.tar.gz

Download URL oidc_python-0.1.0.tar.gz
Size 7.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1e68224dfaad37132176422db3d963dd0b876fd861463bf46753d0191cb18422
BLAKE2b-256 checksum
How to use checksums
d09fef4fb25f0fb5ce8cecf2f5eee33491e6a7b0fe7bd1a7941053ce3aa4e66a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.2

Release files / oidc_python-0.1.0-py3-none-any.whl

Download URL oidc_python-0.1.0-py3-none-any.whl
Size 9.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
46fae6f44462080cd1b0a7f3d0efef6c4449459306382ba24281006009661c10
BLAKE2b-256 checksum
How to use checksums
179ff6b6860feb9bdd3029b681dd43718942540ca28bf3ecac038ca76a1ab265
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.2

Security for oidc-python 0.1.0

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.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page