python requests keycloak

Python Requests Keycloak

If you are trying to implement user authentication and authorization in your Python web application, you may come across the need to integrate your application with Keycloak - an open source Identity and Access Management (IAM) solution. With the help of the Python Requests library, you can easily make HTTP requests to the Keycloak server to authenticate and access protected resources.

Step 1: Install Requests Library

Firstly, you need to install the Requests library in your Python environment. You can do this via pip, the Python package installer, using the following command:

pip install requests

Step 2: Obtain Access Token

To access protected resources in Keycloak, you need to obtain an access token. This token is obtained by sending a POST request to the Keycloak server with your client credentials and user credentials in the request body. The response will contain the access token.

import requests

url = 'http://localhost:8080/auth/realms/myrealm/protocol/openid-connect/token'
data = {
    'grant_type': 'password',
    'client_id': 'myclient',
    'username': 'myuser',
    'password': 'mypassword'
response =, data=data)

if response.status_code == 200:
    access_token = response.json()['access_token']
    print('Unable to obtain access token')

In the above code, replace "myrealm", "myclient", "myuser" and "mypassword" with the actual values for your Keycloak realm, client, user and password respectively. The access token is stored in the "access_token" variable if the request is successful.

Step 3: Access Protected Resource

Now that you have obtained the access token, you can use it to access protected resources in Keycloak by sending HTTP requests with the access token in the "Authorization" header.

import requests

url = 'http://localhost:8080/myprotectedresource'
headers = {
    'Authorization': f'Bearer {access_token}'
response = requests.get(url, headers=headers)

if response.status_code == 200:
    print('Unable to access protected resource')

In the above code, replace "myprotectedresource" with the actual URL of your protected resource. The response from the resource is printed if the request is successful.

Alternatively, you can use the Python Keycloak library, which provides a higher level wrapper around the Keycloak REST API and makes it easier to work with Keycloak in Python.

Hope this helps!