June 20, 2018 By Henrik Loeser 2 min read

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.

Overview

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.

  • The module Flask-pyoidc is an OpenID Connect (OIDC) client for Python and the Flask framework. It interacts with App ID for the authentication.

  • 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:

if 'VCAP_SERVICES' in os.environ:
   vcapEnv=json.loads(os.environ['VCAP_SERVICES'])
   # Obtain configuration for
   appIDInfo = vcapEnv['AppID'][0]['credentials']

The metadata in “appIDInfo” serves as input for the configuration of the OIDC client:

# Configure access to App ID service for the OpenID Connect client
provider_config={
     "issuer": "appid-oauth.ng.bluemix.net",
     "authorization_endpoint": appIDInfo['oauthServerUrl']+"/authorization",
     "token_endpoint": appIDInfo['oauthServerUrl']+"/token",
     "userinfo_endpoint": appIDInfo['profilesUrl']+"/api/v1/attributes",
     "jwks_uri": appIDInfo['oauthServerUrl']+"/publickeys"
}
client_info={
    "client_id": appIDInfo['clientId'],
    "client_secret": appIDInfo['secret']
}

With the configuration in place the OIDC client is initialized:

# Initialize OpenID Connect client
auth = OIDCAuthentication(app, provider_configuration_info=provider_config, client_registration_info=client_info,userinfo_endpoint_method=None)

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:

# Show a user profile
@app.route('/user/profile')
@auth.oidc_auth
def profile():
    return render_template('profile.html',id=flask.session['id_token'], role=flask.session['userrole'])

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.

Conclusions

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.

For details read the full tutorial and deploy the code provided in this GitHub repository.

If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik) or LinkedIn.

Was this article helpful?
YesNo

More from Cloud

How a US bank modernized its mainframe applications with IBM Consulting and Microsoft Azure

9 min read - As organizations strive to stay ahead of the curve in today's fast-paced digital landscape, mainframe application modernization has emerged as a critical component of any digital transformation strategy. In this blog, we'll discuss the example of a US bank which embarked on a journey to modernize its mainframe applications. This strategic project has helped it to transform into a more modern, flexible and agile business. In looking at the ways in which it approached the problem, you’ll gain insights into…

The power of the mainframe and cloud-native applications 

4 min read - Mainframe modernization refers to the process of transforming legacy mainframe systems, applications and infrastructure to align with modern technology and business standards. This process unlocks the power of mainframe systems, enabling organizations to use their existing investments in mainframe technology and capitalize on the benefits of modernization. By modernizing mainframe systems, organizations can improve agility, increase efficiency, reduce costs, and enhance customer experience.  Mainframe modernization empowers organizations to harness the latest technologies and tools, such as cloud computing, artificial intelligence,…

Modernize your mainframe applications with Azure

4 min read - Mainframes continue to play a vital role in many businesses' core operations. According to new research from IBM's Institute for Business Value, a significant 7 out of 10 IT executives believe that mainframe-based applications are crucial to their business and technology strategies. However, the rapid pace of digital transformation is forcing companies to modernize across their IT landscape, and as the pace of innovation continuously accelerates, organizations must react and adapt to these changes or risk being left behind. Mainframe…

IBM Newsletters

Get our newsletters and topic updates that deliver the latest thought leadership and insights on emerging trends.
Subscribe now More newsletters