AuthenticationΒΆ
Keycloak client provides two methods called authentication_url and authentication_callback, using which you can connect to the authentication endpoints of keycloak server easily.
The following snippet is an example written in Flask framework
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #! -*- coding: utf-8 -*-
from flask import Flask, redirect, request, jsonify, session, Response
from keycloak import KeycloakClient
api = Flask(__name__)
api.config['SECRET_KEY'] = 'EYxuFcNqGamVU78GgfupoO5N4z2xokA58XtL0ag'
keycloak_client = KeycloakClient()
@api.route('/login', methods=['GET'])
def login():
""" Initiate authentication """
auth_url, state = keycloak_client.authentication_url()
session['state'] = state
return redirect(auth_url)
@api.route('/login/callback', methods=['GET'])
def login_callback():
""" Authentication callback handler """
code = request.args.get('code')
state = request.args.get('state', 'unknown')
_state = session.pop('state', None)
if state != _state:
return Response('Invalid state', status=403)
response = keycloak_client.authentication_callback(code)
user_info = keycloak_client.decode_jwt(response['id_token'])
return jsonify(user_info)
if __name__ == '__main__':
api.run(host='0.0.0.0')
|