| 1 |
""" |
| 2 |
Copyright 2020-2026 by J. Christopher Wagner (jwag). All rights reserved. |
| 3 |
:license: MIT, see LICENSE for more details. |
| 4 |
|
| 5 |
A simple example of utilizing Flask-Security's OAuth glue layer. |
| 6 |
|
| 7 |
In addition, this example uses unified signin to allow for passwordless registration. |
| 8 |
So users can log in only via social auth OR an email link. |
| 9 |
|
| 10 |
This example also sets up and required CSRF protection for all endpoints. |
| 11 |
|
| 12 |
In order to be self contained, to support things like email confirmation and |
| 13 |
unified sign in with email, we hack a Mail handler that flashes the contents of emails. |
| 14 |
|
| 15 |
This example is designed for a browser based client. |
| 16 |
|
| 17 |
This example uses github as the OAuth provider. Before this example will work: |
| 18 |
1) on github register a new OAuth application and grab the CLIENT_ID and CLIENT_SECRET. |
| 19 |
These must be passed in as env variables: |
| 20 |
"GITHUB_CLIENT_ID" and "GITHUB_CLIENT_SECRET". |
| 21 |
See: https://docs.authlib.org/en/latest/client/flask.html# for details. |
| 22 |
(look under profile->settings->developer settings) |
| 23 |
The redirect_url should be set to https://<your app>/login |
| 24 |
2) Register yourself (with your github email) with this application. |
| 25 |
|
| 26 |
Note: by default this uses an in-memory DB - so everytime you restart you lose all |
| 27 |
registrations. To use a real disk DB: |
| 28 |
set SQLALCHEMY_DATABASE_URI=sqlite:////var/tmp/oauth_example.db |
| 29 |
|
| 30 |
""" |
| 31 |
|
| 32 |
import os |
| 33 |
|
| 34 |
from flask import Flask, flash, render_template_string, redirect |
| 35 |
from flask_security import ( |
| 36 |
Security, |
| 37 |
auth_required, |
| 38 |
FsOAuthProvider, |
| 39 |
MailUtil, |
| 40 |
) |
| 41 |
from flask_wtf import CSRFProtect |
| 42 |
|
| 43 |
from models import db, user_datastore |
| 44 |
|
| 45 |
|
| 46 |
# This is my test tenant on Azure |
| 47 |
class AzureProvider(FsOAuthProvider): |
| 48 |
def authlib_config(self): |
| 49 |
return { |
| 50 |
"api_base_url": "https://graph.microsoft.com/", |
| 51 |
"server_metadata_url": "https://login.microsoftonline.com/" |
| 52 |
"8ad9bf45-2e93-4043-8f46-a6420c8e9d68/v2.0/" |
| 53 |
".well-known/openid-configuration", |
| 54 |
"client_kwargs": {"scope": "openid email profile"}, |
| 55 |
} |
| 56 |
|
| 57 |
def fetch_identity_cb(self, oauth, token): |
| 58 |
profile = token["userinfo"] |
| 59 |
return "email", profile["email"] |
| 60 |
|
| 61 |
|
| 62 |
def _find_bool(v): |
| 63 |
if str(v).lower() in ["true"]: |
| 64 |
return True |
| 65 |
elif str(v).lower() in ["false"]: |
| 66 |
return False |
| 67 |
return v |
| 68 |
|
| 69 |
|
| 70 |
class FlashMailUtil(MailUtil): |
| 71 |
def send_mail( |
| 72 |
self, |
| 73 |
template, |
| 74 |
subject, |
| 75 |
recipients, |
| 76 |
sender, |
| 77 |
body, |
| 78 |
html, |
| 79 |
**kwargs, |
| 80 |
): |
| 81 |
flash(f"Email body: {body}") |
| 82 |
|
| 83 |
|
| 84 |
def create_app(): |
| 85 |
app = Flask(__name__) |
| 86 |
app.config["DEBUG"] = True |
| 87 |
# SECRET_KEY generated using: secrets.token_urlsafe() |
| 88 |
app.config["SECRET_KEY"] = "pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw" |
| 89 |
# PASSWORD_SALT secrets.SystemRandom().getrandbits(128) |
| 90 |
app.config["SECURITY_PASSWORD_SALT"] = "156043940537155509276282232127182067465" |
| 91 |
app.config["SECURITY_TOTP_SECRETS"] = { |
| 92 |
"1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B" |
| 93 |
} |
| 94 |
app.config["SECURITY_TOTP_ISSUER"] = "me" |
| 95 |
# app.config["SESSION_COOKIE_SAMESITE"] = "strict" |
| 96 |
|
| 97 |
# As of Flask-SQLAlchemy 2.4.0 it is easy to pass in options directly to the |
| 98 |
# underlying engine. This option makes sure that DB connections from the pool |
| 99 |
# are still valid. Important for entire application since many DBaaS options |
| 100 |
# automatically close idle connections. |
| 101 |
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_pre_ping": True} |
| 102 |
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 103 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" |
| 104 |
|
| 105 |
# Turn on OAuth glue (github only), passwordless registration (with email link) |
| 106 |
app.config["SECURITY_REGISTERABLE"] = True |
| 107 |
app.config["SECURITY_OAUTH_ENABLE"] = True |
| 108 |
app.config["SECURITY_UNIFIED_SIGNIN"] = True |
| 109 |
app.config["SECURITY_PASSWORD_REQUIRED"] = False |
| 110 |
app.config["SECURITY_US_SIGNIN_REPLACES_LOGIN"] = True |
| 111 |
app.config["SECURITY_US_ENABLED_METHODS"] = ["email"] |
| 112 |
app.config["SECURITY_OAUTH_BUILTIN_PROVIDERS"] = ["github"] |
| 113 |
|
| 114 |
if os.environ.get("SETTINGS"): |
| 115 |
# Load settings from a file pointed to by SETTINGS |
| 116 |
app.config.from_envvar("SETTINGS") |
| 117 |
# Allow any SECURITY_, SQLALCHEMY_ or _CLIENT_ID or _CLIENT_SECRET config |
| 118 |
# to be set in environment. |
| 119 |
for ev in os.environ: |
| 120 |
if ( |
| 121 |
ev.startswith("SECURITY_") |
| 122 |
or ev.startswith("SQLALCHEMY_") |
| 123 |
or "_CLIENT_" in ev |
| 124 |
): |
| 125 |
app.config[ev] = _find_bool(os.environ.get(ev)) |
| 126 |
|
| 127 |
# Enable CSRF on all api endpoints for forms and JSON |
| 128 |
CSRFProtect(app) |
| 129 |
|
| 130 |
# Setup Flask-Security |
| 131 |
db.init_app(app) |
| 132 |
security = Security(app, user_datastore, mail_util_cls=FlashMailUtil) |
| 133 |
# If configured - setup Azure - which works slightly differently - |
| 134 |
# in particular w.r.t. the redirect URL having to match the ENTIRE |
| 135 |
# url including query params (such as next). |
| 136 |
if app.config.get("AZURE_CLIENT_SECRET"): |
| 137 |
security.oauthglue.register_provider_ext(AzureProvider("azure")) |
| 138 |
|
| 139 |
@app.route("/home") |
| 140 |
@auth_required() |
| 141 |
def home(): |
| 142 |
return render_template_string("Hello {{ current_user.email }}") |
| 143 |
|
| 144 |
@app.route("/superfresh") |
| 145 |
@auth_required(within=1, grace=0) |
| 146 |
def superfresh(): |
| 147 |
return render_template_string( |
| 148 |
"Hello {{ current_user.email }} you are super fresh!" |
| 149 |
) |
| 150 |
|
| 151 |
@app.route("/") |
| 152 |
def root(): |
| 153 |
return redirect("/home") |
| 154 |
|
| 155 |
return app |
| 156 |
|
| 157 |
|
| 158 |
if __name__ == "__main__": |
| 159 |
myapp = create_app() |
| 160 |
with myapp.app_context(): |
| 161 |
db.create_all() |
| 162 |
myapp.run(port=5002) |