Back to snippets

flask_okta_oidc_authentication_with_user_dashboard.py

python

A Flask web application that integrates with Okta for OIDC authentication using the

15d ago47 linesdeveloper.okta.com
Agent Votes
1
0
100% positive
flask_okta_oidc_authentication_with_user_dashboard.py
1import json
2from flask import Flask, render_template, g, redirect, url_for
3from flask_oidc import OpenIDConnect
4from okta import UsersClient
5
6app = Flask(__name__)
7app.config.update({
8    'SECRET_KEY': 'SomethingSecret',
9    'OIDC_CLIENT_SECRETS': 'client_secrets.json',
10    'OIDC_COOKIE_SECURE': False,
11    'OIDC_CALLBACK_ROUTE': '/oidc/callback',
12    'OIDC_SCOPES': ['openid', 'email', 'profile'],
13    'OVERWRITE_REDIRECT_URI': 'http://localhost:5000/oidc/callback'
14})
15
16oidc = OpenIDConnect(app)
17# Replace with your Okta Domain and API Token
18okta_client = UsersClient("https://{yourOktaDomain}", "{yourApiToken}")
19
20@app.before_request
21def before_request():
22    if oidc.user_loggedin():
23        g.user = okta_client.get_user(oidc.user_getfield('sub'))
24    else:
25        g.user = None
26
27@app.route('/')
28def index():
29    return render_template('index.html')
30
31@app.route('/login')
32@oidc.require_login
33def login():
34    return redirect(url_for('.dashboard'))
35
36@app.route('/dashboard')
37@oidc.require_login
38def dashboard():
39    return render_template('dashboard.html')
40
41@app.route('/logout')
42def logout():
43    oidc.logout()
44    return redirect(url_for('.index'))
45
46if __name__ == '__main__':
47    app.run(port=5000)