Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple python example using flask, flask_oidc and keycloak, needs a small patch of flask_oidc: https://github.com/puiterwijk/flask-oidc/issues/35
import json
import logging
from flask import Flask, g
from flask_oidc import OpenIDConnect
import requests
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
app.config.update({
'SECRET_KEY': 'SomethingNotEntirelySecret',
'TESTING': True,
'DEBUG': True,
'OIDC_CLIENT_SECRETS': 'client_secrets.json',
'OIDC_ID_TOKEN_COOKIE_SECURE': False,
'OIDC_REQUIRE_VERIFIED_EMAIL': False,
'OIDC_USER_INFO_ENABLED': True,
'OIDC_OPENID_REALM': 'flask-demo',
'OIDC_SCOPES': ['openid', 'email', 'profile'],
'OIDC_INTROSPECTION_AUTH_METHOD': 'client_secret_post'
})
oidc = OpenIDConnect(app)
@app.route('/')
def hello_world():
if oidc.user_loggedin:
return ('Hello, %s, <a href="/private">See private</a> '
'<a href="/logout">Log out</a>') % \
oidc.user_getfield('preferred_username')
else:
return 'Welcome anonymous, <a href="/private">Log in</a>'
@app.route('/private')
@oidc.require_login
def hello_me():
"""Example for protected endpoint that extracts private information from the OpenID Connect id_token.
Uses the accompanied access_token to access a backend service.
"""
info = oidc.user_getinfo(['preferred_username', 'email', 'sub'])
username = info.get('preferred_username')
email = info.get('email')
user_id = info.get('sub')
if user_id in oidc.credentials_store:
try:
from oauth2client.client import OAuth2Credentials
access_token = OAuth2Credentials.from_json(oidc.credentials_store[user_id]).access_token
print 'access_token=<%s>' % access_token
headers = {'Authorization': 'Bearer %s' % (access_token)}
# YOLO
greeting = requests.get('http://localhost:8080/greeting', headers=headers).text
except:
print "Could not access greeting-service"
greeting = "Hello %s" % username
return ("""%s your email is %s and your user_id is %s!
<ul>
<li><a href="/">Home</a></li>
<li><a href="//localhost:8081/auth/realms/pysaar/account?referrer=flask-app&referrer_uri=http://localhost:5000/private&">Account</a></li>
</ul>""" %
(greeting, email, user_id))
@app.route('/api', methods=['POST'])
@oidc.accept_token(require_token=True, scopes_required=['openid'])
def hello_api():
"""OAuth 2.0 protected API endpoint accessible via AccessToken"""
return json.dumps({'hello': 'Welcome %s' % g.oidc_token_info['sub']})
@app.route('/logout')
def logout():
"""Performs local logout by removing the session cookie."""
oidc.logout()
return 'Hi, you have been logged out! <a href="/">Return</a>'
if __name__ == '__main__':
app.run()
{
"web": {
"issuer": "http://localhost:8081/auth/realms/pysaar",
"auth_uri": "http://localhost:8081/auth/realms/pysaar/protocol/openid-connect/auth",
"client_id": "flask-app",
"client_secret": "a41060dd-b5a8-472e-a91f-6a3ab0e04714",
"redirect_uris": [
"http://localhost:5000/*"
],
"userinfo_uri": "http://localhost:8081/auth/realms/pysaar/protocol/openid-connect/userinfo",
"token_uri": "http://localhost:8081/auth/realms/pysaar/protocol/openid-connect/token",
"token_introspection_uri": "http://localhost:8081/auth/realms/pysaar/protocol/openid-connect/token/introspect"
}
}
@anuragchoudhary01

This comment has been minimized.

Copy link

@anuragchoudhary01 anuragchoudhary01 commented Jun 20, 2018

Hi Thomas,

I am trying to validate my RESTService but it is not working. Can you please help here.
Please check the below stack overflow link

https://stackoverflow.com/questions/50895837/how-to-use-keycloak-with-flask-rest-api-service

@rodriguez-facundo

This comment has been minimized.

Copy link

@rodriguez-facundo rodriguez-facundo commented Jun 23, 2019

@thomasdarimont worked like a charm! 💃 🕺 🎉 🌟

@AseedUsmani

This comment has been minimized.

Copy link

@AseedUsmani AseedUsmani commented Feb 12, 2020

Nice! Thanks!

@AseedUsmani

This comment has been minimized.

Copy link

@AseedUsmani AseedUsmani commented Feb 19, 2020

How do we use JWT for setting up client applications? @thomasdarimont

@paco23ch

This comment has been minimized.

Copy link

@paco23ch paco23ch commented Feb 26, 2020

Hi Thomas, do you know if there's a way to instantiate the flask_oidc object without a secrets.json file, but with an actual json object? Thanks!

@oudcheikh

This comment has been minimized.

Copy link

@oudcheikh oudcheikh commented Mar 12, 2020

Hello
what is the configuration to do with keycloak ?
how to get secret file ?

@jornh

This comment has been minimized.

Copy link

@jornh jornh commented Mar 27, 2020

@oudcheikh I think it’s just that Thomas set it up with keycloak, so that’s what he documented (it may/may not work with other providers).

To get the secrets file see https://github.com/puiterwijk/flask-oidc/blob/master/docs/index.rst#registration
There’s also a section for manually making it right below.
See sample format and included fields in https://gist.github.com/thomasdarimont/145dc9aa857b831ff2eff221b79d179a#file-client_secrets-json above

@harish2296

This comment has been minimized.

Copy link

@harish2296 harish2296 commented Aug 13, 2020

can i use this approach without client_secret_key ?

@shashwatagrawal123

This comment has been minimized.

Copy link

@shashwatagrawal123 shashwatagrawal123 commented Oct 19, 2020

<>_<>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.