Skip to content

Authenticating Users with Flask and AuthRamp

This guide will show you how to setup a simple Flask application which authenticates users using AuthRamp. You'll need just a few minutes. Start by creating an AuthRamp application.

Create a test Application

You'll want to create a test application. For our purposes, we'll also populate it with some useful data to test what using AuthRamp is like.

Add AuthRamp Application

We'll leave most settings in their defaults, which are sensible for development.

Create Flask App

Once you've created the application, you'll be presented with four pieces of information to use in our Flask app:

  • API Key
  • OAuth2 Client ID
  • OAuth2 Client Secret
  • Login Page domain name

Note that none of these are necessarily permanent. You can create other API keys, client credentials, and use your own subdomain for authentication if you prefer. But for now, let's proceed with these defaults.

Create a Flask app

Start by creating a Flask app with pip. Make sure you have pipenv installed (or if you prefer, you can use your own preferred alternative, like a virtualenv or docker environment):

$ mkdir flask-example
$ cd flask-example
$ pipenv install
$ pipenv install flask requests authlib

Notice that we're installing flask, requests, and authlib. Now create example.py in the flask-example directory, copying your Client ID, Client Secret, and Domain from the app creation screen.

import json

from authlib.integrations.flask_client import OAuth, FlaskRemoteApp
from flask import Flask, redirect, url_for, request, escape, session

#
# Settings; move to a better place for production
AUTHRAMP_CLIENT_ID = '< YOUR CLIENT ID >'
AUTHRAMP_CLIENT_SECRET = '< YOUR CLIENT SECRET >'
AUTHRAMP_DOMAIN = '< YOUR AUTHRAMP DOMAIN >'
SECRET_KEY = 'change-me'

#
# Create Flask APP
app = Flask(__name__)
app.secret_key = SECRET_KEY

#
# Register OAuth2 provider with authlib
oauth = OAuth()
oauth.init_app(app)

oauth.register(
    name='local',
    client_cls=FlaskRemoteApp,
    client_id=AUTHRAMP_CLIENT_ID,
    client_secret=AUTHRAMP_CLIENT_SECRET,
    server_metadata_url=f'https://{AUTHRAMP_DOMAIN}/.well-known/openid-configuration',
    client_kwargs={
        'scope': 'openid email profile'
    }
)


@app.route('/signup/')
def signup():
    return redirect(f'{AUTHRAMP_DOMAIN}/signup/')


@app.route('/profile/')
def profile():
    return redirect(f'{AUTHRAMP_DOMAIN}/profile/')


@app.route('/login/')
def login():
    # See if we're already logged in
    if session.get('login_session'):
        return redirect(url_for('.hello'))
    else:
        # Login with AuthRamp
        return oauth.local.authorize_redirect(url_for('.auth', _external=True))


@app.route('/auth/')
def auth():
    if request.args.get('error'):
        return f"OAuth2 Error: {escape(request.args.get('error_description', 'Unknown Authorization Error'))}"

    # Get the authorization token and parse the value
    token = oauth.local.authorize_access_token()
    jwt = oauth.local.parse_id_token(token)

    session['login_session'] = jwt

    return redirect(url_for('.hello'))


@app.route('/logout/')
def logout():
    session.pop('login_session', None)
    return redirect(f'https://{AUTHRAMP_DOMAIN}/logout/')


@app.route('/')
def hello():
    if session.get('login_session'):
        jwt_info = json.dumps(session['login_session'], indent=4)
        logout_url = url_for('.logout')
        return f"<h1>You are logged in</h1><pre>{escape(jwt_info)}</pre><a href='{logout_url}'>Logout</a>"
    else:
        login_url = url_for('.login')
        return f'<h1>You are not logged in</h1><a href="{escape(login_url)}">Login Here</a>'


if __name__ == '__main__':
    app.run(port=8080)

Run the app:

$ pipenv shell
$ python example.py

Once the app runs, you'll be able to login, logout, and see your profile information inside your Flask app. Simple as that.