Securing Python-Flask application using flask-oidc and keycloak server

adkarigar
1 min readJun 15, 2020

--

requirements

Docker Toolbox in case of windows

downloading the jboss/keycloak image from jboss

install flask, flask-oidc,requests packages

app.py

import json
import logging
import os
from flask import Flask, g
from flask_oidc import OpenIDConnect
import requests
logging.basicConfig(level=logging.DEBUG)app.config["OIDC_CLIENT_SECRETS"]="client_secrets.json"
app.config["OIDC_COOKIE_SECURE"]=False
app.config["OIDC_CALLBACK_ROUTE"]='/*'
app.config["OIDC_SCOPES"]=["openid","email","profile"]
app.config["SECRET_KEY"]="SomethingSecret"
app.config["TESTING"]=True
app.config["DEBUG"] = True
app.config["OIDC_ID_TOKEN_COOKIE_SECURE"]=False
app.config["OIDC_REQUIRED_VERIFIED_EMAIL"]=False
app.config['OIDC_INTROSPECTION_AUTH_METHOD"]='client_secret_post'
app.config["OIDC_USER_INFO_ENABLED"]=True
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://192.168.99.100:5000/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="//192.168.99.100:8080/auth/realms/karigar/account?referrer=flask-app&referrer_uri=http://localhost:5000/private&">Account</a></li>
</ul>""" %
(greeting, email, user_id))

--

--

No responses yet