> For the complete documentation index, see [llms.txt](https://ztrust.gitbook.io/ztrust-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ztrust.gitbook.io/ztrust-documentation/user-manual-ztrust-v4.2/5.-securing-applications/5.4-securing-a-python-application.md).

# 5.4 Securing a Python Application

ZTrust integrates with **Python** using **OpenID Connect (OIDC)** to handle authentication and authorization. This setup enables secure login and role-based access for your applications.

### Prerequisites

Before integrating your Spring Boot application with ZTrust, ensure the following are in place:

* **ZTrust SSO** – A running ZTrust instance that will act as the identity and access management provider.
* **Configured Realm and Client** – A realm and client must already be created in ZTrust, with the client configured for OIDC. These settings will be used by your Python app to authenticate users and validate tokens.

With these prerequisites, your application will be ready to establish a secure connection with ZTrust using OpenID Connect.

### Set up ZTrust

1. Log in to ZTrust Admin Console.<br>

   <figure><img src="/files/De9Ji5EdPL5oiui6VEYU" alt=""><figcaption><p>Fig 5.4.a: Master realm welcome page</p></figcaption></figure>

2. Click on **Manage Realms** in the sidebar to view the list of realms available in your **ZTrust**.<br>

   <figure><img src="/files/HDTBGt1691z2nPZAxymB" alt=""><figcaption><p>Fig 5.4.b: List of avalible realms under manage realms</p></figcaption></figure>

3. From the list of realms, select the **realm** where you want to integrate the Python Application.<br>

   <figure><img src="/files/SkZd1tHHm1y0nNSCPa7u" alt=""><figcaption><p>Fig 5.4.c: Welcome to Demo realm</p></figcaption></figure>

4. From the left **sidebar**, navigate to the **Clients** section.<br>

   <figure><img src="/files/FDbQy4gBO8hQROxTlEds" alt="" width="96"><figcaption><p>Fig 5.4.d: Navigating to clients section in side bar</p></figcaption></figure>

5. You will see a list of **clients** (applications). Choose/ Create the **client** for which you want to secure Python Application.

   <figure><img src="/files/wbw7aaAVaLcOJJw9b9Au" alt=""><figcaption><p>Fig 5.4.e: List of available clients</p></figcaption></figure>

6. After select your client, it will take you to the settings page

   <figure><img src="/files/UTBJppyzagOBNDgKpsxh" alt=""><figcaption><p>Fig 5.4.f: Client settings page</p></figcaption></figure>

7. Enter your application’s **redirect URL** in the **Valid Redirect URIs** field.<br>

   <figure><img src="/files/OjCPYkmmQm31TQEOOwTG" alt=""><figcaption><p>Fig 5.4.g: In client settings tab general settings fields</p></figcaption></figure>

8. Then under **Capability** config turn on **Client authentication** and save<br>

   <figure><img src="/files/MMLwFgCZDvwjJEAAj5ZV" alt="" width="563"><figcaption><p>Fig 5.4.h: In client settings tab capability config options</p></figcaption></figure>

9. You will now see a new tab enabled, called **Credentials**.

   <figure><img src="/files/ip0Dw6JyYfOBTv32E3yA" alt=""><figcaption><p>Fig 5.4.i: Client settings tab</p></figcaption></figure>

10. Navigate to the **Credentials** tab, where you can view and copy the **Client Secret**.

    <figure><img src="/files/8jux6tIJavqE6whEV99y" alt=""><figcaption><p>Fig 5.4.j: Navigating to Credentials tab</p></figcaption></figure>

11. With the ZTrust configuration complete, we can now move on to the Python side of the setup.

### Set up Python

**1. Load ZTrust Configuration**

The application reads ZTrust authentication details (URL, realm, client ID, secret) from  environment variables. &#x20;

```
ZTRUST_AUTH_URL = os.getenv("ZTRUST_AUTH_URL")
ZTRUST_REALM = os.getenv("ZTRUST_REALM")
ZTRUST_CLIENT_ID = os.getenv("ZTRUST_CLIENT_ID")
ZTRUST_CLIENT_SECRET = os.getenv("ZTRUST_CLIENT_SECRET")
```

**2. Fetch ZTrust Public Keys (JWKS)**

&#x20;  Python application retrieves ZTrust’s official public keys to validate tokens.

```
JWKS_URL = f"{ZTRUST_AUTH_URL}/realms/{ZTRUST_REALM}/protocol/openid-connect/certs"
jwks_data = requests.get(JWKS_URL).json()
```

**3. Validate User Token**

When a user logs in, ZTrust issues a JWT (JSON Web Token).The app verifies the token and extracts user identity details.

```python
def get_current_user(token: str = Depends(OAUTH2_SCHEME)) -> dict:
    payload = jwt.decode(
        token,
        key=get_public_key(token),
        algorithms=['RS256']
    )
```

**4. Enforce Role-Based Access**

User roles (e.g., Admin, SuperAdmin, User) are checked before allowing actions.

```python
def role_checker(required_role: list[str]):
    def wrapper(user: dict = Depends(get_current_user)):
        roles = user.get("realm_access", {}).get("roles", [])
        if not any(role in roles for role in required_role):
            raise HTTPException(status_code=403, detail="Missing required role")
        return user
    return wrapper
```

**5. Authentication & Security Dependencies**

To implement secure authentication and integration with ZTrust, the following Python libraries were used:

* python-jose (3.5.0) – For handling JWT (JSON Web Token) encoding, decoding, and validation.
* python-multipart (0.0.9) – For managing form data and file uploads in FastAPI requests.
* requests (2.32.3) – For making HTTP requests, such as retrieving ZTrust’s public keys (JWKS).
* python-dotenv (1.0.1) – For securely loading environment variables (authentication URLs, client IDs, secrets) without hardcoding them in the codebase.
