Keycloak Client Readthedocs Io en Stable
Keycloak Client Readthedocs Io en Stable
Release 1.2.0
Akhil Lawrence
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
5
Keycloak Client Documentation, Release 1.2.0
6 Chapter 2. Implementation
CHAPTER 3
Core APIs
7
Keycloak Client Documentation, Release 1.2.0
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
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
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
41
42 if __name__ == '__main__':
43 api.run(host='0.0.0.0')
4.2 Authorization
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()
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
10 Chapter 4. Extensions
Keycloak Client Documentation, Release 1.2.0
1 #! /usr/bin/env python
2 from flask import Flask
3
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)
1 #! /usr/bin/env python
2 import uvicorn
3
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)
12 Chapter 4. Extensions