Skip to main content

Flask Cognito Authentication

Project description

Flask-Cognito-Auth

License: MIT PyPI CircleCI

Flask-Cognito-Auth is a Flask implementation of AWS Cognito Service with User Pool. This extension helps to implement authentication solutions based on AWS's Cognito Service. It contains helpful functions and properties to handle oauth2 and token based authentication flows. This extension requires to enable "Enabled Identity Providers" in Appllication client settings of User Pool within AWS Cognito Sevice.

Add Application


SAML Assertion settings (OPTIONAL)

If SAML provider is set then optionally SAML assertion can be set and reterieved post authentication.
These assertions are reterived under Session object under key "saml_assertions".

Example

SAML Assertion

* Replace "Email" with the key provided in SAML assertions sent by IDP and to be reterived as Email key.
* Replace "MemberOf" with the key provided in SAML assertions sent by IDP and to be reterived as profile key.
* Add as many assertions required post authentication.
pip install flask-cognito-auth

Usage

from flask import Flask
from flask import redirect
from flask import url_for
from flask import session
from flask import jsonify
from flask_cognito_auth import CognitoAuthManager
from flask_cognito_auth import login_handler
from flask_cognito_auth import logout_handler
from flask_cognito_auth import callback_handler

app = Flask(__name__)
app.secret_key = "my super secret key"

# Setup the flask-cognito-auth extention
app.config['COGNITO_REGION'] = "us-east-1"
app.config['COGNITO_USER_POOL_ID'] = "us-east-1_xxxxxxx"
app.config['COGNITO_CLIENT_ID'] = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
app.config['COGNITO_CLIENT_SECRET'] = "xxxxxxxxxxxxxxxxxxxxxxxxxx"
app.config['COGNITO_DOMAIN'] = "https://yourdomainhere.com"
app.config["ERROR_REDIRECT_URI"] = "page500"        # Optional
app.config["COGNITO_STATE"] = "mysupersecrethash"   # Optional

app.config['COGNITO_REDIRECT_URI'] = "https://yourdomainhere/cognito/callback"  # Specify this url in Callback URLs section of Appllication client settings of User Pool within AWS Cognito Sevice. Post login application will redirect to this URL

app.config['COGNITO_SIGNOUT_URI'] = "https://yourdomainhere/login" # Specify this url in Sign out URLs section of Appllication client settings of User Pool within AWS Cognito Sevice. Post logout application will redirect to this URL


cognito = CognitoAuthManager(app)
# cognito = CognitoManager(app)
# cognito.init(app)


@app.route('/login', methods=['GET'])
def login():
    print("Do the stuff before login to AWS Cognito Service")
    response = redirect(url_for("cognitologin"))
    return response


@app.route('/logout', methods=['GET'])
def logout():
    print("Do the stuff before logout from AWS Cognito Service")
    response = redirect(url_for("cognitologout"))
    return response


# Use @login_handler decorator on cognito login route
@app.route('/cognito/login', methods=['GET'])
@login_handler
def cognitologin():
    pass


@app.route('/home', methods=['GET'])
def home():
    current_user = session["username"]
    return jsonify(logged_in_as=current_user), 200


# Use @callback_handler decorator on your cognito callback route
@app.route('/cognito/callback', methods=['GET'])
@callback_handler
def callback():
    print("Do the stuff before post successfull login to AWS Cognito Service")
    for key in list(session.keys()):
        print(f"Value for {key} is {session[key]}")
    response = redirect(url_for("home"))
    return response


# Use @logout_handler decorator on your cognito logout route
@app.route('/cognito/logout', methods=['GET'])
@logout_handler
def cognitologout():
    pass


@app.route('/page500', methods=['GET'])
def page500():
    return jsonify(Error="Something went wrong"), 500


if __name__ == '__main__':
    app.run(debug=True)

Development Setup

Using pipenv

pipenv install --dev 

Using virtualenv

python3 -m venv env
source env/bin/activate
pip install .

Contributing

  1. Fork repo- https://github.com/shrivastava-v-ankit/flask-cognito-auth.git
  2. Create your feature branch - git checkout -b feature/name
  3. Add Python test (pytest) and covrage report for new/changed feature.
  4. Commit your changes - git commit -am "Added name"
  5. Push to the branch - git push origin feature/name
  6. Create a new pull request

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask-cognito-auth-1.1.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

flask_cognito_auth-1.1.0-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file flask-cognito-auth-1.1.0.tar.gz.

File metadata

  • Download URL: flask-cognito-auth-1.1.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.23.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.8.5

File hashes

Hashes for flask-cognito-auth-1.1.0.tar.gz
Algorithm Hash digest
SHA256 d9c6b1ba6b8d53d5aad31c9b7ea4bc118ee303a01832294743b8bc7738acc78a
MD5 7497444e9f932d0c7f5d4bd777555625
BLAKE2b-256 3395551837f3322bb79a4cf0e9b6c32e97dc8831ef5660e7a58432e089b845bf

See more details on using hashes here.

File details

Details for the file flask_cognito_auth-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: flask_cognito_auth-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.6.1 requests/2.23.0 setuptools/50.3.1.post20201107 requests-toolbelt/0.9.1 tqdm/4.62.0 CPython/3.8.5

File hashes

Hashes for flask_cognito_auth-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 01fcf13c79985f1474fd30b826197cd809d67789dc9522b84c50ed6f61eb5c3c
MD5 0bafabf5384db774bb25547cd7d1f44a
BLAKE2b-256 3169f07e87e827d2bd069f089cd6e3764efcbe121abbd2478585d53ec0e4dbc4

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page