Skip to content

Instantly share code, notes, and snippets.

@asyd
Created October 4, 2024 12:03
Show Gist options
  • Save asyd/d75aff298d74566d7c1ad50262473958 to your computer and use it in GitHub Desktop.
Save asyd/d75aff298d74566d7c1ad50262473958 to your computer and use it in GitHub Desktop.
flask_dance keycloak usage example
# Since redirect_url is not in https, ensure you set OAUTHLIB_INSECURE_TRANSPORT environment varaible
from flask import Flask, jsonify, request, redirect, url_for
from flask_dance.consumer import OAuth2ConsumerBlueprint
app = Flask(__name__)
app.secret_key = 'xxx'
keycloak = OAuth2ConsumerBlueprint(
name="keycloak",
import_name=__name__,
client_id='flask-dance',
client_secret='xxxx',
base_url='https://<keycloak url>/auth/realms/<realm name>/',
# despite documentation say, relative URLs for token_url and authorization_url doesn't work here
token_url='https://<keycloak url>/auth/realms/<realm name>//protocol/openid-connect/token',
authorization_url='https://<keycloak url>/auth/realms/<realm name>//protocol/openid-connect/auth',
redirect_url='http://localhost:5000/authenticated',
# You must defined scope, otherwhise keycloak will refused to respond to userinfo
scope='openid email profile',
)
app.register_blueprint(keycloak, url_prefix='/login')
@app.route('/authenticated')
def index():
if not keycloak.session.authorized:
return redirect(url_for('keycloak.login'))
resp = keycloak.session.get('protocol/openid-connect/userinfo')
assert resp.ok
return resp.json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment