Skip to main content

This project developed for intagration OICD in your project

Project description

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

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

oidc_python-0.1.0.tar.gz (7.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

oidc_python-0.1.0-py3-none-any.whl (9.5 kB view details)

Uploaded Python 3

File details

Details for the file oidc_python-0.1.0.tar.gz.

File metadata

  • Download URL: oidc_python-0.1.0.tar.gz
  • Upload date:
  • Size: 7.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.2

File hashes

Hashes for oidc_python-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1e68224dfaad37132176422db3d963dd0b876fd861463bf46753d0191cb18422
MD5 3f74af7086127d98861e294e3d77f7b9
BLAKE2b-256 d09fef4fb25f0fb5ce8cecf2f5eee33491e6a7b0fe7bd1a7941053ce3aa4e66a

See more details on using hashes here.

File details

Details for the file oidc_python-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for oidc_python-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 46fae6f44462080cd1b0a7f3d0efef6c4449459306382ba24281006009661c10
MD5 c50318ba0d0e7fe3db1aa0c450704f44
BLAKE2b-256 179ff6b6860feb9bdd3029b681dd43718942540ca28bf3ecac038ca76a1ab265

See more details on using hashes here.

Supported by

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