python requests keycloak login

Python Requests Keycloak Login

As a developer, I have worked with different APIs and integrated them into my applications. One of the common problems I faced was authentication and authorization. Keycloak is an open-source identity and access management solution that provides authentication and authorization services. In this article, I will explain how to use Python Requests module to login to Keycloak.

Prerequisites

  • A Keycloak server running
  • Python 3 installed on your machine
  • Requests module installed: You can install it using pip.

Login to Keycloak using Python Requests Library

The following steps will guide you on how to use Python Requests module to login to Keycloak.

Step 1: Getting the Login Form

You need to make a GET request to the Keycloak login page to get the login form. You can use the requests module's get() method for this. You will need to provide the Keycloak URL and realm name in the URL.


import requests

url = 'http://localhost:8080/auth/realms/YourRealmName/protocol/openid-connect/auth'
response = requests.get(url)

Step 2: Submitting the Login Form

After getting the form, you will need to fill in the required fields and submit the form. The required fields are usually username, password, and some hidden fields that are generated dynamically by Keycloak. You can use BeautifulSoup library to parse the HTML form and find these fields. Then, you can use requests module's post() method to submit the form.


from bs4 import BeautifulSoup

# Parse the form
soup = BeautifulSoup(response.content, 'html.parser')
form = soup.find('form')
action = form['action']

# Find the required fields
username = form.find('input', attrs={'name': 'username'})['value']
password = form.find('input', attrs={'name': 'password'})['value']
other_fields = {i['name']: i['value'] for i in form.findAll('input', {'type': 'hidden'})}

# Submit the form
response = requests.post(action, data={
    'username': username,
    'password': password,
    **other_fields
})

After successful submission of the login form, you will be redirected to the Keycloak dashboard page. You can verify that by checking the response status code, which should be 200. In case of failed login, the status code will be 401.

Step 3: Retrieving the Access Token

Now that we are logged in, we need to retrieve the access token to access protected resources. The access token is usually returned in the response body as a JSON object. We can use the requests module's json() method to parse the JSON object.


access_token = response.json()['access_token']

Conclusion

In this article, we learned how to use Python Requests module to login to Keycloak. We first got the login form, then filled in the required fields and submitted the form. Finally, we retrieved the access token from the response body. We can now use this access token to access protected resources.