# Connecting with Python

This guide explains how to establish a connection between a Python Flask application and a Keycloak identity provider using <span class="s2">Flask-OIDC</span>. It walks through the necessary setup, configuration, and usage of a protected route that requires authentication.

## **Variables**

Certain parameters must be provided to integrate a Python Flask application with Keycloak. Below is a breakdown of each required variable, its purpose, and where to find it. Here’s what each variable represents:

<table border="1" id="bkmrk-variable-description" style="width: 100%; border-collapse: collapse; border-color: rgb(0, 0, 0);"><thead><tr><th style="width: 18.1145%; border-color: rgb(0, 0, 0);">**Variable**

</th><th style="width: 43.0297%; border-color: rgb(0, 0, 0);">**Description**

</th><th style="width: 38.8558%; border-color: rgb(0, 0, 0);">**Purpose**

</th></tr></thead><tbody><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`CLIENT_ID`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Client ID from the Keycloak Clients page

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Identifies the Flask app in the Keycloak realm

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`CLIENT_SECRET`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Secret from the Credentials tab of the client

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Authenticates the Flask app with Keycloak

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`ISSUER`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);"><span class="s1">Full Keycloak realm URL (e.g. </span>https://your-domain/realms/your-realm<span class="s1">)</span>

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Defines the OpenID Connect issuer

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`REDIRECT_URI`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">The callback URL Keycloak will redirect to after login

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used by Flask-OIDC to complete login flow

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`TOKEN_ENDPOINT`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">Token URL from Keycloak

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used for exchanging authorization codes for access tokens

</td></tr><tr><td style="width: 18.1145%; border-color: rgb(0, 0, 0);">`USERINFO_ENDPOINT`

</td><td style="width: 43.0297%; border-color: rgb(0, 0, 0);">User info endpoint from Keycloak

</td><td style="width: 38.8558%; border-color: rgb(0, 0, 0);">Used to fetch user profile after login

</td></tr></tbody></table>

These values can be found in the <span class="s1">**Keycloak Admin Console**</span> under <span class="s1">**Clients → \[Your Client\] → Settings / Credentials / Endpoints**</span>. Make sure to copy and add them to the code as shown.

## **Prerequisites**

#### **Install Python and pip**

Check if Python is installed by running:

```
python3 --version
```

If not installed, download it from [https://python.org](https://python.org) and install.

Verify <span class="s1">pip</span> installation:

```
pip3 --version
```

#### **Install Required Packages**

Install the required Python packages using:

```
pip3 install flask flask-oidc
```

## **Code**

Once all prerequisites are set up, create a new file named <span class="s2">app.py</span> and add the following code:

```python
from flask import Flask, redirect, url_for, jsonify
from flask_oidc import OpenIDConnect

app = Flask(__name__)

# Keycloak OIDC configuration (no JSON file required)
app.config.update({
    'SECRET_KEY': 'your-random-secret',
    'OIDC_CLIENT_SECRETS': {
        "web": {
            "client_id": "CLIENT_ID",
            "client_secret": "CLIENT_SECRET",
            "auth_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/auth",
            "token_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/token",
            "userinfo_uri": "https://your-keycloak-domain/realms/your-realm/protocol/openid-connect/userinfo",
            "redirect_uris": ["http://localhost:5000/oidc/callback"]
        }
    },
    'OIDC_SCOPES': ['openid', 'email', 'profile'],
    'OIDC_CALLBACK_ROUTE': '/oidc/callback',
    'OIDC_COOKIE_SECURE': False
})

oidc = OpenIDConnect(app)

@app.route('/')
def index():
    return 'Welcome to the public route.'

@app.route('/protected')
@oidc.require_login
def protected():
    user_info = oidc.user_getinfo(['email', 'sub', 'name'])
    return jsonify({
        "message": "You are authenticated",
        "user": user_info
    })

@app.route('/logout')
def logout():
    oidc.logout()
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)
```

Replace the placeholders in the <span class="s1">client\_id</span>, <span class="s1">client\_secret</span>, and URL fields with actual values from your Keycloak instance.

## **Execution**

Open the terminal and navigate to the directory where <span class="s1">app.py</span> is saved. Once in the correct directory, run the script with the command:

```
python3 app.py
```

If the connection is successful:

1. Open <span class="s1">http://localhost:5000</span> in your browser — Public route.
2. Open <span class="s1">http://localhost:5000/protected</span> — Redirects to Keycloak login.
3. After logging in, you’ll see user info returned from the protected route.
4. Visit <span class="s1">http://localhost:5000/logout</span> to end the session and return to the public page.