Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active May 11, 2024 09:57
Show Gist options
  • Save thomasdarimont/145dc9aa857b831ff2eff221b79d179a to your computer and use it in GitHub Desktop.
Save thomasdarimont/145dc9aa857b831ff2eff221b79d179a to your computer and use it in GitHub Desktop.
Simple python example using flask, flask_oidc and keycloak
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"
}
}
@AseedUsmani
Copy link

Hi all, @thomasdarimont - I'm looking for a full example of keycloak client config and a secured flask app. Please can anyone point me in the right direction for a working example? Thank you!

@phil-doyle-369 this is pretty much ready (as a demo only). What is confusing you?

@phil-doyle-369
Copy link

Hi @AseedUsmani,

@phil-doyle-369 this is pretty much ready (as a demo only). What is confusing you?

Well I setup keycloak on a server and have the app.py service running on localhost:5000. I visit the localhost:5000 and see a login link which redirects me to keycloak to login. The login is successful as I can see the user session in the keycloak admin.

When keycloak redirects back to the Flask service the oidc_callback throws the following error.

http://localhost:5000/oidc_callback?state=eyJjc3JmX3Rva2VuIjogIkpuODlvREdTMkdNQzl5QWZPdGZ0UVh4NGNFTkNTa2NhIiwgImRlc3RpbmF0aW9uIjogImV5SmhiR2NpT2lKSVV6VXhNaUo5LkltaDBkSEE2THk5c2IyTmhiR2h2YzNRNk5UQXdNQzl3Y21sMllYUmxJZy5NZ0lfU0puaktXMTg4TTBuZFdKZWw2YXhicFZjR2NLTzFBQ3ducURheXQtUlQ1ckxuX2RCd0FYcFozR2x5eTBqbU1nZ1dGdnJPQzZOZ01kbl9KQVNDQSJ9&session_state=8c4b100f-d50f-4853-9e9b-1f020a16d61f&code=faecc443-65f0-4199-b76d-4819b14adc8b.8c4b100f-d50f-4853-9e9b-1f020a16d61f.0917bdbe-6a63-4a58-b1ea-16c97e0d3547

Traceback (most recent call last):
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2464, in call
return self.wsgi_app(environ, start_response)
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/phild/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/phild/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/phild/.local/lib/python3.6/site-packages/flask_oidc/init.py", line 657, in _oidc_callback
plainreturn, data = self._process_callback('destination')
File "/home/phild/.local/lib/python3.6/site-packages/flask_oidc/init.py", line 689, in _process_callback
credentials = flow.step2_exchange(code)
File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/client.py", line 2054, in step2_exchange
http, self.token_uri, method='POST', body=body, headers=headers)
File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/transport.py", line 282, in request
connection_type=connection_type)
File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 1314, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 1064, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 987, in _conn_request
conn.connect()
File "/home/phild/anaconda3/envs/runner6/lib/python3.6/http/client.py", line 1448, in connect
server_hostname=server_hostname)
File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 407, in wrap_socket
_context=self, _session=session)
File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 817, in init
self.do_handshake()
File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 1077, in do_handshake
self._sslobj.do_handshake()
File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 689, in do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)

I also tried running the Flask service in a docker container as a reverse proxy on the same server as the keycloak server (also in a docker container) and this gives the following error.

phild@dmz-werkstatt-00:~$ docker logs test-svr

  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
  • Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
    192.168.0.7 - - [30/Mar/2022 13:34:40] "GET /test-svr/ HTTP/1.0" 200 -
    192.168.0.7 - - [30/Mar/2022 13:34:45] "GET /test-svr/private HTTP/1.0" 302 -
    192.168.0.7 - - [30/Mar/2022 13:35:06] "GET /test-svr/oidc_callback?state=eyJjc3JmX3Rva2VuIjogInhRTkdTUXVseEVhb2VQaUQ2TDYwekZUNTl6bHk3aUZqIiwgImRlc3RpbmF0aW9uIjogImV5SmhiR2NpT2lKSVV6VXhNaUo5LkltaDBkSEE2THk5M1pYSnJjM1JoZEhRdVlYTjBjbWwyYVhNdVkyOXRMM1JsYzNRdGMzWnlMM0J5YVhaaGRHVWkudjdQTHdReTl1Y0ZjcDZZZEw0Yzkzd2VBbzU2cHNiVTJDNG5KNG12MVFhYldkOHZiZ21fVTREbkJ0VmJqUmttNzB0TDhpOWRkZU5ETjl1VUZwZlExblEifQ%3D%3D&session_state=271a337f-894b-44e2-8100-7fc44115f613&code=bf7ad4e5-fc6c-42f8-b3fb-f6f4c5e01161.271a337f-894b-44e2-8100-7fc44115f613.0917bdbe-6a63-4a58-b1ea-16c97e0d3547 HTTP/1.0" 404 -

Any ideas regarding the issue would be much appreciated.

@albertwibowo
Copy link

Hello, a quick question. Does the client_secrets.json have to be in the following format?

{
"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"
}
}

@neerajasjawali
Copy link

Hello.
Flask-OIDC is not working in 32bit R-Pi server board.
Could anyone help me to solve this issue?
Could you suggest some alternatives for flask-oidc packages and dJango packages?

@jouellnyc
Copy link

jouellnyc commented May 7, 2022

This was a terrific launching point for me. There's a lot of examples on the 'net that are dead ends or just don't work. Thank so much

@volodya-wtf
Copy link

Hi, i need help please! After adding apache as a reverse proxy and dockerization, I get a redirect to the ip address of the container and not back to the application. And as a consequence: "not authorized"

Apache config:

<Location /api_gateway>
ProxyPass http://172.18.0.16:5000/
ProxyPassReverse http://172.18.0.16:5000/

@1zg12
Copy link

1zg12 commented Jul 20, 2022

Hi @AseedUsmani,

@phil-doyle-369 this is pretty much ready (as a demo only). What is confusing you?

Well I setup keycloak on a server and have the app.py service running on localhost:5000. I visit the localhost:5000 and see a login link which redirects me to keycloak to login. The login is successful as I can see the user session in the keycloak admin.

When keycloak redirects back to the Flask service the oidc_callback throws the following error.

http://localhost:5000/oidc_callback?state=eyJjc3JmX3Rva2VuIjogIkpuODlvREdTMkdNQzl5QWZPdGZ0UVh4NGNFTkNTa2NhIiwgImRlc3RpbmF0aW9uIjogImV5SmhiR2NpT2lKSVV6VXhNaUo5LkltaDBkSEE2THk5c2IyTmhiR2h2YzNRNk5UQXdNQzl3Y21sMllYUmxJZy5NZ0lfU0puaktXMTg4TTBuZFdKZWw2YXhicFZjR2NLTzFBQ3ducURheXQtUlQ1ckxuX2RCd0FYcFozR2x5eTBqbU1nZ1dGdnJPQzZOZ01kbl9KQVNDQSJ9&session_state=8c4b100f-d50f-4853-9e9b-1f020a16d61f&code=faecc443-65f0-4199-b76d-4819b14adc8b.8c4b100f-d50f-4853-9e9b-1f020a16d61f.0917bdbe-6a63-4a58-b1ea-16c97e0d3547

Traceback (most recent call last): File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2464, in call return self.wsgi_app(environ, start_response) File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app response = self.handle_exception(e) File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception reraise(exc_type, exc_value, tb) File "/home/phild/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/phild/.local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/phild/.local/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "/home/phild/.local/lib/python3.6/site-packages/flask_oidc/init.py", line 657, in _oidc_callback plainreturn, data = self._process_callback('destination') File "/home/phild/.local/lib/python3.6/site-packages/flask_oidc/init.py", line 689, in _process_callback credentials = flow.step2_exchange(code) File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper return wrapped(*args, **kwargs) File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/client.py", line 2054, in step2_exchange http, self.token_uri, method='POST', body=body, headers=headers) File "/home/phild/.local/lib/python3.6/site-packages/oauth2client/transport.py", line 282, in request connection_type=connection_type) File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 1314, in request (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 1064, in _request (response, content) = self._conn_request(conn, request_uri, method, body, headers) File "/home/phild/.local/lib/python3.6/site-packages/httplib2/init.py", line 987, in _conn_request conn.connect() File "/home/phild/anaconda3/envs/runner6/lib/python3.6/http/client.py", line 1448, in connect server_hostname=server_hostname) File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 407, in wrap_socket _context=self, _session=session) File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 817, in init self.do_handshake() File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 1077, in do_handshake self._sslobj.do_handshake() File "/home/phild/anaconda3/envs/runner6/lib/python3.6/ssl.py", line 689, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)

I also tried running the Flask service in a docker container as a reverse proxy on the same server as the keycloak server (also in a docker container) and this gives the following error.

phild@dmz-werkstatt-00:~$ docker logs test-svr

  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
  • Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
    192.168.0.7 - - [30/Mar/2022 13:34:40] "GET /test-svr/ HTTP/1.0" 200 -
    192.168.0.7 - - [30/Mar/2022 13:34:45] "GET /test-svr/private HTTP/1.0" 302 -
    192.168.0.7 - - [30/Mar/2022 13:35:06] "GET /test-svr/oidc_callback?state=eyJjc3JmX3Rva2VuIjogInhRTkdTUXVseEVhb2VQaUQ2TDYwekZUNTl6bHk3aUZqIiwgImRlc3RpbmF0aW9uIjogImV5SmhiR2NpT2lKSVV6VXhNaUo5LkltaDBkSEE2THk5M1pYSnJjM1JoZEhRdVlYTjBjbWwyYVhNdVkyOXRMM1JsYzNRdGMzWnlMM0J5YVhaaGRHVWkudjdQTHdReTl1Y0ZjcDZZZEw0Yzkzd2VBbzU2cHNiVTJDNG5KNG12MVFhYldkOHZiZ21fVTREbkJ0VmJqUmttNzB0TDhpOWRkZU5ETjl1VUZwZlExblEifQ%3D%3D&session_state=271a337f-894b-44e2-8100-7fc44115f613&code=bf7ad4e5-fc6c-42f8-b3fb-f6f4c5e01161.271a337f-894b-44e2-8100-7fc44115f613.0917bdbe-6a63-4a58-b1ea-16c97e0d3547 HTTP/1.0" 404 -

Any ideas regarding the issue would be much appreciated.

Are you running keycloak out of HTTPS ? You need to have that cert added in your trust store in the python service if that's the case.

@reddybhavaniprasad
Copy link

reddybhavaniprasad commented Oct 25, 2022

Hi,
I am able to authorize the APIs using the keycloak token generated from the client secret. Now I have an extra use case where I have two different DNS to reach keycloak, I have added one of them in the client_secrets.json file. When I generate the access token using the other (different) DNS and authorize the API, they are failing with 401 error but with the access token generated from the DNS configured in the client_secrets.json file it is successful.
Please let me know if there is any way I can update both the keycloak endpoints in the client_secrets.json file.

@otto2704
Copy link

Hi,
thanks for this example. It works so far. But now I have to add some dash stuff.
Dash needs a function for layout. As soon as I am using this, the oidc stuff does not work anymore (and oidc is not recognised within the layout function). Does anyone maybe have a working example for flask plus dash and could post it?

@robertoneto-senior
Copy link

robertoneto-senior commented Feb 8, 2024

For logout I was only able to do it with:

@app.route('/signout')
def logout():
    id_token = session.get('oidc_auth_token').get('id_token')
    return redirect(
        "https://my-key-cloak/realms/my-realm/protocol/openid-connect/logout?id_token_hint=%s&post_logout_redirect_uri=%s" % (id_token, urllib.parse.quote("http://localhost/logout", safe='')))

The signout process will logout on keycloak and redirect to /logout to discard cookies.

And I changed the link on main page to point to /signout instead of /logout.

This "fix" was based on keycloak 18 upgrade docs:

@alex27riva
Copy link

Hi everyone, does this code still works?
It seems that the endpoints have changed from http://localhost:8081/auth/realms/pysaar to http://localhost:8081/realms/pysaar

I tried to run the app but I get this error message:
immagine

Maybe because this method is not resolved:
immagine

@LUCIFERsDen26
Copy link

LUCIFERsDen26 commented Mar 12, 2024

Hello! @alex27riva

I got it working! 🎉 GitHub Gist Link

docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.1 start-dev

Then I built the realm and client, and modified the code according to the latest release of flask-oidc (1.2.0) (Sep 28, 2017).

Thank you!

If you've discovered a new way to deal with Flask Keycloak, please let me know too!

@alex27riva
Copy link

Hello! @alex27riva

I got it working! 🎉 GitHub Gist Link

docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.1 start-dev

Then I built the realm and client, and modified the code according to the latest release of flask-oidc (1.2.0) (Sep 28, 2017).

Thank you!

If you've discovered a new way to deal with Flask Keycloak, please let me know too!

Hi @LUCIFERsDen26 , thank your for your reply.
I tried your code, but I'm getting the same error as before.
immagine
Are these client setting correct?

@LUCIFERsDen26
Copy link

Hello! @alex27riva
I got it working! 🎉 GitHub Gist Link

docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:24.0.1 start-dev

Then I built the realm and client, and modified the code according to the latest release of flask-oidc (1.2.0) (Sep 28, 2017).
Thank you!
If you've discovered a new way to deal with Flask Keycloak, please let me know too!

Hi @LUCIFERsDen26 , thank your for your reply. I tried your code, but I'm getting the same error as before. immagine Are these client setting correct?

Hey!
thanks for reaching out!
the adress should be same as you python flask app is running on like shown in image!

BTW it has username : lucifer
password: test (i guess, i dont remenber, i change it from admin account)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment