Skip to main content

Python клиент для взаимодействия с MS Auth Service API

Project description

SSO Nebus Client

Python клиент для взаимодействия с MS Auth Service API. Предоставляет удобные классы для работы с OAuth 2.0 Authorization Code Flow с PKCE (для пользователей) и Client Credentials Grant (для микросервисов).

Установка

pip install -e .

Или если пакет опубликован:

pip install sso_nebus

Быстрый старт

Для пользователей (UserClient)

import asyncio
from sso_client import UserClient

async def main():
    # Создаем клиент
    client = UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id",
        redirect_uri="http://localhost:3000/callback"
    )
    
    # Полный цикл авторизации
    token_response = await client.full_auth_flow(
        login="user@example.com",
        password="password123",
        scope="sso.admin.read sso.admin.create"
    )
    
    print(f"Access token: {token_response.access_token}")
    print(f"Refresh token: {token_response.refresh_token}")
    
    # Получаем информацию о пользователе
    user_info = await client.get_current_user()
    print(f"Пользователь: {user_info.name} {user_info.surname}")
    
    # Обновляем токен
    new_token = await client.refresh_access_token()
    print(f"Новый access token: {new_token.access_token}")
    
    await client.close()

asyncio.run(main())

Пошаговая авторизация

import asyncio
from sso_client import UserClient

async def main():
    client = UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id"
    )
    
    # 1. Получаем PKCE параметры
    pkce_params = await client.get_pkce_params()
    
    # 2. Инициируем авторизацию
    auth_response = await client.authorize(
        scope="sso.admin.read",
        pkce_params=pkce_params
    )
    
    # 3. Выполняем логин
    login_response = await client.login(
        login="user@example.com",
        password="password123",
        session_id=auth_response.session_id
    )
    
    # 4. Обмениваем код на токены
    token_response = await client.exchange_code_for_tokens(
        authorization_code=login_response.authorization_code,
        pkce_params=pkce_params
    )
    
    print(f"Токены получены: {token_response.access_token}")
    
    await client.close()

asyncio.run(main())

Для микросервисов (ServiceClient)

import asyncio
from sso_client import ServiceClient

async def main():
    # Создаем клиент для микросервиса
    client = ServiceClient(
        base_url="http://localhost:8000",
        client_id="service_id",
        client_secret="service_secret"
    )
    
    # Получаем access token
    token_response = await client.get_access_token(
        scope="system.client.read system.client.edit"
    )
    
    print(f"Access token: {token_response.access_token}")
    
    # Выполняем запросы с авторизацией
    user_info = await client.get_current_user()
    
    # Или используем request_with_auth для любых endpoints
    data = await client.request_with_auth(
        method="GET",
        endpoint="admin/users",
        params={"skip": 0, "limit": 10}
    )
    
    await client.close()

asyncio.run(main())

Использование с async context manager

import asyncio
from sso_client import UserClient

async def main():
    async with UserClient(
        base_url="http://localhost:8000",
        client_id="your_client_id"
    ) as client:
        token_response = await client.full_auth_flow(
            login="user@example.com",
            password="password123"
        )
        # Сессия автоматически закроется при выходе

asyncio.run(main())

API Reference

UserClient

Класс для пользовательского взаимодействия с OAuth 2.0 Authorization Code Flow с PKCE.

Методы

  • get_pkce_params() - Получить PKCE параметры от сервера
  • authorize(scope, redirect_uri, pkce_params) - Инициировать OAuth 2.0 flow
  • login(login, password, session_id) - Выполнить аутентификацию
  • exchange_code_for_tokens(authorization_code, redirect_uri, pkce_params) - Обменять код на токены
  • refresh_access_token(refresh_token) - Обновить access token
  • get_current_user(access_token) - Получить информацию о пользователе
  • logout(refresh_token) - Выйти из системы
  • get_available_services() - Получить список доступных микросервисов
  • full_auth_flow(login, password, scope, redirect_uri) - Выполнить полный цикл авторизации

ServiceClient

Класс для микросервисного взаимодействия с Client Credentials Grant.

Методы

  • get_access_token(scope) - Получить access token
  • get_current_user(access_token) - Получить информацию о текущем пользователе/сервисе
  • request_with_auth(method, endpoint, json_data, params, auto_refresh) - Выполнить запрос с авторизацией

Исключения

  • SSOClientError - Базовое исключение
  • AuthenticationError - Ошибка аутентификации (401)
  • AuthorizationError - Ошибка авторизации (403)
  • APIError - Ошибка API (4xx, 5xx)
  • TokenError - Ошибка работы с токенами

Лицензия

MIT

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

sso_nebus-0.1.1.tar.gz (12.3 kB view details)

Uploaded Source

Built Distribution

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

sso_nebus-0.1.1-py3-none-any.whl (17.8 kB view details)

Uploaded Python 3

File details

Details for the file sso_nebus-0.1.1.tar.gz.

File metadata

  • Download URL: sso_nebus-0.1.1.tar.gz
  • Upload date:
  • Size: 12.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.10 Windows/11

File hashes

Hashes for sso_nebus-0.1.1.tar.gz
Algorithm Hash digest
SHA256 55eab71a2f8bcb3f4687e3d07a94285dc46398dc2e9513e70dcc3306e36cf095
MD5 cffbd17d550e4ea97d8e560238ff5b7c
BLAKE2b-256 83c48e94993e170458069b302c1d9e2006004d5920b32a6f0c4537ed95207cf9

See more details on using hashes here.

File details

Details for the file sso_nebus-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: sso_nebus-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 17.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.10 Windows/11

File hashes

Hashes for sso_nebus-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d5cb42622989853d7fa18b2368cd3dd8e1d4320b566037b826353a47de974919
MD5 9c93ea27bb3f8c542233dc278be4486a
BLAKE2b-256 da8770382c6e5e2d9758c0bd40155294020635416857649ff87d4d7845495980

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