0% found this document useful (0 votes)
62 views16 pages

Keycloak Client Readthedocs Io en Stable

The document provides documentation for the Keycloak client library, which allows for easy integration of Keycloak authentication and authorization features into Python applications. It describes the core APIs and extensions for frameworks like Flask, Django, and Starlette. Authentication can be performed using the login and callback methods, while authorization uses PAT and permission tickets. Examples are provided for initializing the client and integrating authentication into Flask and Starlette apps.

Uploaded by

yendrys blanco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views16 pages

Keycloak Client Readthedocs Io en Stable

The document provides documentation for the Keycloak client library, which allows for easy integration of Keycloak authentication and authorization features into Python applications. It describes the core APIs and extensions for frameworks like Flask, Django, and Starlette. Authentication can be performed using the login and callback methods, while authorization uses PAT and permission tickets. Examples are provided for initializing the client and integrating authentication into Flask and Starlette apps.

Uploaded by

yendrys blanco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Keycloak Client Documentation

Release 1.2.0

Akhil Lawrence

Aug 06, 2021


Features

1 Examples 3

2 Implementation 5

3 Core APIs 7

4 Extensions 9
4.1 Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.2 Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.3 Using Flask Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.4 Using Starlette Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.5 Using Django Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.6 API Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

i
ii
Keycloak Client Documentation, Release 1.2.0

Keycloak is an open source identity and access management (IAM) solution for the modern application and services.
To know more about keycloak, please visit their official website. The focus of this library is to provide easy integration
with keycloak server, so that the features like authentication, authorization etc can be used in a python applications
very easily.

Features 1
Keycloak Client Documentation, Release 1.2.0

2 Features
CHAPTER 1

Examples

https://github.com/keycloak-client/keycloak-client/tree/main/examples

3
Keycloak Client Documentation, Release 1.2.0

4 Chapter 1. Examples
CHAPTER 2

Implementation

This library consists of two sections


• Core APIs
• Extensions

5
Keycloak Client Documentation, Release 1.2.0

6 Chapter 2. Implementation
CHAPTER 3

Core APIs

These consists of the core interactions with the keycloak server.

7
Keycloak Client Documentation, Release 1.2.0

8 Chapter 3. Core APIs


CHAPTER 4

Extensions

These consists of middleware implementations for standard frameworks like Flask, Django etc. Extensions are imple-
mented using core APIs. While integrating keycloak with your app, either you can use the core APIs directly or you
can use prebuilt extensions.

4.1 Authentication

Keycloak client provides two methods called login and callback, using which you can connect to the authentication
endpoints of keycloak server and perform openid authentication easily.
The following snippet is an example written in Flask framework

1 #! -*- coding: utf-8 -*-


2 from flask import Flask, redirect, request, jsonify, session, Response
3 from keycloak import Client
4

6 api = Flask(__name__)
7 api.config['SECRET_KEY'] = 'EYxuFcNqGamVU78GgfupoO5N4z2xokA58XtL0ag'
8 kc = Client()
9

10

11 @api.route('/login', methods=['GET'])
12 def login():
13 """ Initiate authentication """
14 url, state = kc.login()
15 session['state'] = state
16 return redirect(url)
17

18

19 @api.route('/login/callback', methods=['GET'])
20 def login_callback():
21 """ Authentication callback handler """
(continues on next page)

9
Keycloak Client Documentation, Release 1.2.0

(continued from previous page)


22

23 # validate state
24 state = request.args.get('state', 'unknown')
25 _state = session.pop('state', None)
26 if state != _state:
27 return Response('Invalid state', status=403)
28

29 # retrieve tokens
30 code = request.args.get('code')
31 tokens = kc.callback(code)
32

33 # retrieve userinfo
34 access_token = tokens["access_token"]
35 userinfo = kc.fetch_userinfo(access_token)
36 session["user"] = userinfo
37

38 # send userinfo to user


39 return jsonify(userinfo)
40

41

42 if __name__ == '__main__':
43 api.run(host='0.0.0.0')

4.2 Authorization

Authorization is performed with the help of UMA (User Managed Access)

4.2.1 Generating PAT

PAT (Protection API Token) is a special token with scope uma_protection. Keycloak provides a method called pat
using with you can retrieve the PAT token.
1 #! -*- coding: utf-8 -*-
2 from keycloak import Client
3

4 kc = Client()
5 kc.pat()

4.2.2 Generating Permission Ticket

A permission ticket is a special type of token defined by the User-Managed Access (UMA) specification that provides
an opaque structure whose form is determined by the authorization server. This structure represents the resources
and/or scopes being requested by a client, the access context, as well as the policies that must be applied to a request
for authorization data. See this for more details.
1 #! -*- coding: utf-8 -*-
2 from keycloak import Client
3

4 kc = Client()
5 pat = kc.pat()
6

(continues on next page)

10 Chapter 4. Extensions
Keycloak Client Documentation, Release 1.2.0

(continued from previous page)


7 resources = [
8 {
9 "resource_id": "8762039c-cdfa-4ef9-9f70-45248863c4da",
10 "resource_scopes": ["create", "read", "update", "delete]
11 }
12 ]
13 ticket = kc.find_ticket(resources, pat["access_token"]

4.3 Using Flask Extension

1 #! /usr/bin/env python
2 from flask import Flask
3

4 from keycloak.extensions.flask import AuthenticationMiddleware


5

6 app = Flask(__name__)
7 app.config["SECRET_KEY"] = "secret0123456789"
8

10 app.wsgi = AuthenticationMiddleware(
11 app.wsgi,
12 app.config,
13 app.session_interface,
14 callback_url="http://localhost:5000/kc/callback",
15 redirect_uri="/howdy",
16 logout_uri="/logout"
17 )
18

19

20 @app.route("/howdy")
21 def howdy():
22 return "Howdy!"
23

24 @app.route("/logout")
25 def logout():
26 return "User logged out!"
27

28

29 if __name__ == "__main__":
30 app.run(debug=True)

4.4 Using Starlette Extension

1 #! /usr/bin/env python
2 import uvicorn
3

4 from starlette.applications import Starlette


5 from starlette.middleware.sessions import SessionMiddleware
6 from starlette.responses import PlainTextResponse
7

8 from keycloak.extensions.starlette import AuthenticationMiddleware


(continues on next page)

4.3. Using Flask Extension 11


Keycloak Client Documentation, Release 1.2.0

(continued from previous page)


9

10

11 app = Starlette()
12 app.debug = True
13 app.add_middleware(AuthenticationMiddleware, callback_url="http://localhost:8000/kc/
˓→callback", redirect_uri="/howdy", logout_uri="/logout")

14 app.add_middleware(SessionMiddleware, secret_key="secret0123456789")
15

16

17 @app.route("/howdy")
18 def howdy(request):
19 return PlainTextResponse("Howdy!")
20

21

22 @app.route("/logout")
23 def logout(request):
24 return PlainTextResponse("User logged out!")
25

26

27 if __name__ == "__main__":
28 uvicorn.run(app)

4.5 Using Django Extension

Please see the examples available in https://github.com/keycloak-client/keycloak-client/tree/main/examples

4.6 API Reference

12 Chapter 4. Extensions

You might also like