Skip to content

Instantly share code, notes, and snippets.

@saintsGrad15
Last active September 26, 2023 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saintsGrad15/32afc80a1d610ec4098e9057bfaac3da to your computer and use it in GitHub Desktop.
Save saintsGrad15/32afc80a1d610ec4098e9057bfaac3da to your computer and use it in GitHub Desktop.
Basic Flask application using IBMid SSO
{
"client_secrets": {
"web": {
"auth_uri": "<Retrieve from IBMid registration>",
"client_id": "<your_client_id>",
"client_secret": "<your_client_secret>",
"token_uri": "<Retrieve from IBMid registration>",
"token_introspection_uri": "<Retrieve from IBMid registration>",
"issuer": "<Retrieve from IBMid registration>"
}
}
}
# Flask docs: http://flask.pocoo.org/docs/1.0/
# Flask-oidc docs: https://flask-oidc.readthedocs.io/en/latest/
from flask_oidc import OpenIDConnect
from flask import (Flask,
render_template)
flask_application = Flask("SOME APP NAME", static_folder="app/static")
flask_application.secret_key = "some random secret not actually stored in source control" # http://flask.pocoo.org/docs/1.0/api/?highlight=secret_key#flask.Flask.secret_key
flask_application.config.update({
# Or whatever name you gave the file
# I haven't tried but you might be able to give it the dict directly...
# See attached file.
"OIDC_CLIENT_SECRETS": "path/to/client_secrets.json"
})
oidc = OpenIDConnect(flask_application)
flask_application.run(host="localhost",
port=1234,
use_reloader=True,
debug=True)
@flask_application.route("/home")
@oidc.require_login
def home(*args, **kwargs):
"""
This route will only be returned if the user is logged in.
If they are not, redirection will take place and, once authenticated
they will be redirected back to this view.
"""
# A file located in the directory passed to "static_folder" in the Flask constructor above
return render_template("index.html")
@flask_application.route("/api/ping")
def ping():
"""
This API explictly checks for the user's authenticity below and will conduct whatever logic you want.
I had my client side logic detect the 401 status code and send them to the my login route (defined further down)
in a separate window. Once authenticated the user can hit the API again.
"""
if not oidc.user_loggedin:
return "User not logged in.", 401, {}
return "Pong", 200, {}
@flask_application.route("/login")
@oidc.require_login
def login():
"""
In my implementation this template just tells the user they successfully logged in
and then closes itself allowing the user to return to the page that sent them here.
"""
return render_template("login_successful.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment