Securing your Python app with OpenID Connect (OIDC)
Some weeks back I introduced to a tutorial on how to analyse GitHub traffic. The tutorial combines serverless technology and Cloud Foundry to automatically retrieve statistics and store them in Db2. The data can then be accessed and analyzed using a Python Flask app. Today, I am going to show you how the web site is protected using OpenID Connect and IBM Cloud App ID.
For the GitHub Traffic Analytics app, the statistics are fetched automatically and stored in Db2. Users access the data via a Python app based on the Flask microframework. Visualization is based on Cognos Dashboard Embedded. User management (authentication and authorization) is realized through the following combination:
Architecture – Traffic Analytics
IBM Cloud App ID provides the authentication service. It provides a wrap around identity providers, ranging from social logins (Facebook, Goggle) over Cloud Directory to SAML-based enterprise user directories.
User roles and provileges are stored in Db2 Warehouse on Cloud along the statistics. The user information provided in the authentication token determines the accessible data sets and related privileges.
Configure OpenID Connect client
Assuming the Python app is deployed on Cloud Foundry, the credentials for the App ID service can be obtained the following way:
The metadata in “appIDInfo” serves as input for the configuration of the OIDC client:
With the configuration in place the OIDC client is initialized:
Protect web routes
After the configuration, the OpenID Client can be used to protect individual pages or sections (“routes”) of the web app. This is done by attaching an additional decorator to the route definition:
The code “@auth.oidc_auth” is the decorator. It makes sure that the code is only executed for authenticated users. In the code snippet above you see that information from an “id_token” and a “userrole” are passed for processing. I will discuss the role-based privileges and the user managed realized with Db2 in a follow-up blog post.
Using IBM Cloud App ID together with an OpenID Connect client, it is fairly simple to protect routes (web pages) in a Python Flask app. The two combined allow to use social identity providers such as Facebook and Google, the Cloud Directory provided by App ID, or even enterprise user directories based on the SAML protocol.