Skip to main content

This is a library project for the authentication using the basic auth and oidc

Project description

ZMP Authentication Provider

A Python library for authentication using Basic Auth and OIDC (OpenID Connect).

Description

This library provides authentication functionality using both Basic Authentication and OpenID Connect protocols. It's designed to be flexible and easy to integrate into your Python applications.

Installation

pip install zmp-authentication-provider

Requirements

  • Python >= 3.12, < 4.0

Dependencies

  • pydantic >= 2.10.6
  • pydantic-settings >= 2.9.1, < 3.0.0
  • fastapi >= 0.115.11, < 0.116.0
  • python-dotenv >= 1.0.1, < 2.0.0
  • pyjwt >= 2.10.1, < 3.0.0
  • requests >= 2.32.3, < 3.0.0
  • cryptography >= 42.0.0, < 45.0
  • pymongo >= 4.12.0, < 5.0.0
  • motor >= 3.7.0, < 4.0.0

Usage

# FastAPI main.py
from zmp_authentication_provider.routes.auth import router as auth_router
from zmp_authentication_provider.service.auth_service import AuthService

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan for the FastAPI app."""
    try:
        # 8. Initialize AIOps Service
        app.state.aiops_service = AIOpsService.initialize(database=database)
        logger.info("AIOps Service initialized")

        yield

    finally:
        ...

app = FastAPI(
    # root_path=f"{application_settings.root_path}",
    title=f"{application_settings.title}",
    description=f"{application_settings.description}",
    version=f"{application_settings.version}",
    docs_url=f"{application_settings.docs_url}",
    openapi_url=f"{application_settings.openapi_url}",
    redoc_url=f"{application_settings.redoc_url}",
    default_response_class=JSONResponse,
    debug=True,
    # servers=server,
    root_path_in_servers=True,
    lifespan=lifespan,
)


app.include_router(auth_router, tags=["auth"], prefix=application_settings.root_path)


# router.py
from zmp_authentication_provider.auth.oauth2_keycloak import (
    TokenData,
    get_current_user,
)


@router.put(
    "/jobs/{job_id}",
    summary="Update job details",
    description="Update the details of an existing job. Only the provided fields will be updated.",
    response_description="The updated job information.",
    response_class=JSONResponse,
    response_model=Job,
    response_model_by_alias=False,
    response_model_exclude_none=False,
)
async def update_job(
    job_update_request: JobUpdateRequest,
    job_id: str = Path(..., description="The ID of the job to update"),
    service: AIOpsService = Depends(_get_aiops_service),
    oauth_user: TokenData = Depends(get_current_user),
):
    """Update a job's information."""
    job = Job(
        id=job_id,
        updated_by=oauth_user.username,
        **job_update_request.model_dump(exclude_unset=True),
    )
    return await service.modify_job(job=job)

Sliding Session Management

To implement sliding session expiration (automatic session extension on user activity), add the following middleware to your FastAPI application:

from typing import Callable
from fastapi import Request, Response
from zmp_authentication_provider.utils.redis_session_store import redis_session_store
from zmp_authentication_provider.setting import auth_default_settings

@app.middleware("http")
async def sliding_session_middleware(
    request: Request, call_next: Callable[[Request], Response]
):
    """Sliding session middleware."""
    session_id = request.cookies.get(auth_default_settings.session_id_cookie_name)
    if session_id:
        session = await redis_session_store.get(session_id)  # Redis GET
        if session:
            # sliding expiration for the session of the redis session store
            await redis_session_store.reset_ttl(session_id)

    resp: Response = await call_next(request)

    # if the session is changed or the sliding expiration is maintained, the cookie is also updated
    if session_id:
        resp.set_cookie(
            key=auth_default_settings.session_id_cookie_name,
            value=session_id,
            max_age=auth_default_settings.session_max_age,
            httponly=auth_default_settings.session_https_only,
            secure=auth_default_settings.session_secure,
            samesite=auth_default_settings.session_same_site,
            domain=auth_default_settings.session_domain,
        )
    return resp

This middleware automatically extends the session expiration time on every request, ensuring users remain logged in while actively using the application.

Environment Configuration

Put the below value into the.env file in your project root:

# Authentication default configuration
AUTH_HTTP_CLIENT_SSL_VERIFY="True"
AUTH_APPLICATION_ENDPOINT="${AIOPS_API_ENDPOINT}"

# Keycloak configuration
KEYCLOAK_SERVER_URL="https://keycloak.ags.cloudzcp.net/auth"
KEYCLOAK_REALM="ags"
KEYCLOAK_CLIENT_ID="zmp-client"
KEYCLOAK_CLIENT_SECRET="p4W697V2t9WXSh3kCnCfSCt4MHK4myYG"
KEYCLOAK_REDIRECT_URI="${AUTH_APPLICATION_ENDPOINT}/oauth2/callback"
KEYCLOAK_ALGORITHM="RS256"

Development

Development Dependencies

pip install pytest pytest-cov pytest-watcher pytest-asyncio certifi ruff

Quality Tools

pip install pre-commit

Project Structure

The main package is located in the src/zmp_authentication_provider directory.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the terms of the license included in the repository.

Author

Links

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

zmp_authentication_provider-0.3.1.tar.gz (20.2 kB view details)

Uploaded Source

Built Distribution

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

zmp_authentication_provider-0.3.1-py3-none-any.whl (27.3 kB view details)

Uploaded Python 3

File details

Details for the file zmp_authentication_provider-0.3.1.tar.gz.

File metadata

  • Download URL: zmp_authentication_provider-0.3.1.tar.gz
  • Upload date:
  • Size: 20.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.3 Darwin/24.5.0

File hashes

Hashes for zmp_authentication_provider-0.3.1.tar.gz
Algorithm Hash digest
SHA256 877b9dfa4cc7788e7a8690935b9cd02a3d255923bf68e5cdd37ff0aa2e46ec13
MD5 7d9426cb107686263b8c6bcd97f40ac9
BLAKE2b-256 c3e9429484219dea0bb490c4ffe529cd1572c26e0db5f2618d2abe2714d11f78

See more details on using hashes here.

File details

Details for the file zmp_authentication_provider-0.3.1-py3-none-any.whl.

File metadata

File hashes

Hashes for zmp_authentication_provider-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f0c0df749b6a1783dbc07cc034125bf42d84a965ac0cff718b0a186f4080ec90
MD5 dbb720c74ab0b6f828159357e6e3986a
BLAKE2b-256 30cd81b164323bfe32a28b0c8cab763fa21354dc96ae54d14c2b8745d95ac9c0

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