flask-cognito-lib


Nameflask-cognito-lib JSON
Version 1.5.0 PyPI version JSON
download
home_pagehttps://github.com/mblackgeo/flask-cognito-lib
SummaryA Flask extension that supports protecting routes with AWS Cognito following OAuth 2.1 best practices
upload_time2023-07-12 09:39:54
maintainer
docs_urlNone
authormblackgeo
requires_python>=3.8,<4.0
licenseMIT
keywords flask extension oauth cognito
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Protect Flask routes with AWS Cognito

[![PyPI](https://img.shields.io/pypi/v/flask_cognito_lib?style=for-the-badge)](https://pypi.org/project/flask-cognito-lib/)
[![Docs](https://img.shields.io/github/actions/workflow/status/mblackgeo/flask-cognito-lib/docs.yml?label=DOCS&style=for-the-badge)](https://mblackgeo.github.io/flask-cognito-lib)
[![CI](https://img.shields.io/github/actions/workflow/status/mblackgeo/flask-cognito-lib/cicd.yml?label=CI&style=for-the-badge)](https://github.com/mblackgeo/flask-cognito-lib/actions)
[![codecov](https://img.shields.io/codecov/c/github/mblackgeo/flask-cognito-lib?style=for-the-badge&token=TGV2RMGNZ5)](https://codecov.io/gh/mblackgeo/flask-cognito-lib)

A Flask extension that supports protecting routes with AWS Cognito following [OAuth 2.1 best practices](https://oauth.net/2.1/). That means the full authorization code flow, including Proof Key for Code Exchange (RFC 7636) to prevent Cross Site Request Forgery (CSRF), along with secure storage of access tokens in HTTP only cookies (to prevent Cross Site Scripting attacks), and additional `nonce` validation (if using ID tokens) to prevent replay attacks.

**Documentation**: [https://mblackgeo.github.io/flask-cognito-lib](https://mblackgeo.github.io/flask-cognito-lib)

**Source Code**: [https://github.com/mblackgeo/flask-cognito-lib](https://github.com/mblackgeo/flask-cognito-lib)


## Installation

Use the package manager [pip](https://pip.pypa.io/en/stable/) to install:

```bash
pip install flask-cognito-lib
```


## Quick start

To get started quickly, a complete example Flask application is provided in [`/example`](example/) including instructions on setting up a Cognito User Pool. A separate repo holds [a complete example app](https://github.com/mblackgeo/flask-cognito-jwt-example), including AWS CDK (Cloud Development Kit) code to deploy the application to API Gateway and Lambda, along with creation of a Cognito User Pool and Client. However, assuming a Cognito user pool has been setup with an app client (with Client ID and Secret), get started as follows:

```python
from flask import Flask, jsonify, redirect, session, url_for

from flask_cognito_lib import CognitoAuth
from flask_cognito_lib.decorators import (
    auth_required,
    cognito_login,
    cognito_login_callback,
    cognito_logout,
)

app = Flask(__name__)

# Configuration required for CognitoAuth
app.config["AWS_REGION"] = "eu-west-1"
app.config["AWS_COGNITO_USER_POOL_ID"] = "eu-west-1_qwerty"
app.config["AWS_COGNITO_DOMAIN"] = "https://app.auth.eu-west-1.amazoncognito.com"
app.config["AWS_COGNITO_USER_POOL_CLIENT_ID"] = "asdfghjkl1234asdf"
app.config["AWS_COGNITO_USER_POOL_CLIENT_SECRET"] = "zxcvbnm1234567890"
app.config["AWS_COGNITO_REDIRECT_URL"] = "https://example.com/postlogin"
app.config["AWS_COGNITO_LOGOUT_URL"] = "https://example.com/postlogout"

auth = CognitoAuth(app)


@app.route("/login")
@cognito_login
def login():
    # A simple route that will redirect to the Cognito Hosted UI.
    # No logic is required as the decorator handles the redirect to the Cognito
    # hosted UI for the user to sign in.
    # An optional "state" value can be set in the current session which will
    # be passed and then used in the postlogin route (after the user has logged
    # into the Cognito hosted UI); this could be used for dynamic redirects,
    # for example, set `session['state'] = "some_custom_value"` before passing
    # the user to this route
    pass


@app.route("/postlogin")
@cognito_login_callback
def postlogin():
    # A route to handle the redirect after a user has logged in with Cognito.
    # This route must be set as one of the User Pool client's Callback URLs in
    # the Cognito console and also as the config value AWS_COGNITO_REDIRECT_URL.
    # The decorator will store the validated access token in a HTTP only cookie
    # and the user claims and info are stored in the Flask session:
    # session["claims"] and session["user_info"].
    # Do anything after the user has logged in here, e.g. a redirect or perform
    # logic based on a custom `session['state']` value if that was set before
    # login
    return redirect(url_for("claims"))


@app.route("/claims")
@auth_required()
def claims():
    # This route is protected by the Cognito authorisation. If the user is not
    # logged in at this point or their token from Cognito is no longer valid
    # a 401 Authentication Error is thrown, which can be caught by registering
    # an `@app.error_handler(AuthorisationRequiredError)
    # If their auth is valid, the current session will be shown including
    # their claims and user_info extracted from the Cognito tokens.
    return jsonify(session)


@app.route("/admin")
@auth_required(groups=["admin"])
def admin():
    # This route will only be accessible to a user who is a member of all of
    # groups specified in the "groups" argument on the auth_required decorator
    # If they are not, a 401 Authentication Error is thrown, which can be caught
    # by registering an `@app.error_handler(CognitoGroupRequiredError).
    # If their auth is valid, the set of groups the user is a member of will be
    # shown.

    # Could also use: jsonify(session["user_info"]["cognito:groups"])
    return jsonify(session["claims"]["cognito:groups"])


@app.route("/edit")
@auth_required(groups=["admin", "editor"], any_group=True)
def edit():
    # This route will only be accessible to a user who is a member of any of
    # groups specified in the "groups" argument on the auth_required decorator
    # If they are not, a CognitoGroupRequiredError is raised which is handled
    # below
    return jsonify(session["claims"]["cognito:groups"])


@app.route("/logout")
@cognito_logout
def logout():
    # Logout of the Cognito User pool and delete the cookies that were set
    # on login.
    # No logic is required here as it simply redirects to Cognito.
    pass


@app.route("/postlogout")
def postlogout():
    # This is the endpoint Cognito redirects to after a user has logged out,
    # handle any logic here, like returning to the homepage.
    # This route must be set as one of the User Pool client's Sign Out URLs.
    return redirect(url_for("home"))


if __name__ == "__main__":
    app.run()
```


## Development

Prequisites:

* [poetry](https://python-poetry.org/)
* [pre-commit](https://pre-commit.com/)

The Makefile includes helpful commands setting a development environment, get started by installing the package into a new environment and setting up pre-commit by running `make install`. Run `make help` to see additional available commands (e.g. linting, testing and so on).

* [Pytest](https://docs.pytest.org/en/6.2.x/) is used for testing the application (see `/tests`).
* [MkDocs](https://www.mkdocs.org/) is used for generating docs and hosted with GH pages (see `/docs`).
* Code is linted using [flake8](https://flake8.pycqa.org/en/latest/)
* Code formatting is validated using [Black](https://github.com/psf/black)
* [pre-commit](https://pre-commit.com/) is used to run these checks locally before files are pushed to git
* The [Github Actions pipeline](.github/workflows/cicd.yml) runs these checks and tests
* [Semantic-release](https://python-semantic-release.readthedocs.io/en/latest/) is used with [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) for automated releasing to PyPI


## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate and ensure 100% test coverage.


## Credits

This work started as a fork of the unmaintained [Flask-AWSCognito](https://github.com/cgauge/Flask-AWSCognito) extension, revising the implementation following OAuth 2.1 recommendations, with inspiration from [flask-cognito-auth](https://github.com/shrivastava-v-ankit/flask-cognito-auth). Whilst there are serveral Cognito extensions available for Flask, none of those implement OAuth 2.1 recommendations, with some plugins not even actively maintained.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mblackgeo/flask-cognito-lib",
    "name": "flask-cognito-lib",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "Flask,Extension,OAuth,Cognito",
    "author": "mblackgeo",
    "author_email": "18327836+mblackgeo@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/aa/33/56d5975d5d2be27442da80ef76bf9f8d696f0d78a072ad403a812816b311/flask_cognito_lib-1.5.0.tar.gz",
    "platform": null,
    "description": "# Protect Flask routes with AWS Cognito\n\n[![PyPI](https://img.shields.io/pypi/v/flask_cognito_lib?style=for-the-badge)](https://pypi.org/project/flask-cognito-lib/)\n[![Docs](https://img.shields.io/github/actions/workflow/status/mblackgeo/flask-cognito-lib/docs.yml?label=DOCS&style=for-the-badge)](https://mblackgeo.github.io/flask-cognito-lib)\n[![CI](https://img.shields.io/github/actions/workflow/status/mblackgeo/flask-cognito-lib/cicd.yml?label=CI&style=for-the-badge)](https://github.com/mblackgeo/flask-cognito-lib/actions)\n[![codecov](https://img.shields.io/codecov/c/github/mblackgeo/flask-cognito-lib?style=for-the-badge&token=TGV2RMGNZ5)](https://codecov.io/gh/mblackgeo/flask-cognito-lib)\n\nA Flask extension that supports protecting routes with AWS Cognito following [OAuth 2.1 best practices](https://oauth.net/2.1/). That means the full authorization code flow, including Proof Key for Code Exchange (RFC 7636) to prevent Cross Site Request Forgery (CSRF), along with secure storage of access tokens in HTTP only cookies (to prevent Cross Site Scripting attacks), and additional `nonce` validation (if using ID tokens) to prevent replay attacks.\n\n**Documentation**: [https://mblackgeo.github.io/flask-cognito-lib](https://mblackgeo.github.io/flask-cognito-lib)\n\n**Source Code**: [https://github.com/mblackgeo/flask-cognito-lib](https://github.com/mblackgeo/flask-cognito-lib)\n\n\n## Installation\n\nUse the package manager [pip](https://pip.pypa.io/en/stable/) to install:\n\n```bash\npip install flask-cognito-lib\n```\n\n\n## Quick start\n\nTo get started quickly, a complete example Flask application is provided in [`/example`](example/) including instructions on setting up a Cognito User Pool. A separate repo holds [a complete example app](https://github.com/mblackgeo/flask-cognito-jwt-example), including AWS CDK (Cloud Development Kit) code to deploy the application to API Gateway and Lambda, along with creation of a Cognito User Pool and Client. However, assuming a Cognito user pool has been setup with an app client (with Client ID and Secret), get started as follows:\n\n```python\nfrom flask import Flask, jsonify, redirect, session, url_for\n\nfrom flask_cognito_lib import CognitoAuth\nfrom flask_cognito_lib.decorators import (\n    auth_required,\n    cognito_login,\n    cognito_login_callback,\n    cognito_logout,\n)\n\napp = Flask(__name__)\n\n# Configuration required for CognitoAuth\napp.config[\"AWS_REGION\"] = \"eu-west-1\"\napp.config[\"AWS_COGNITO_USER_POOL_ID\"] = \"eu-west-1_qwerty\"\napp.config[\"AWS_COGNITO_DOMAIN\"] = \"https://app.auth.eu-west-1.amazoncognito.com\"\napp.config[\"AWS_COGNITO_USER_POOL_CLIENT_ID\"] = \"asdfghjkl1234asdf\"\napp.config[\"AWS_COGNITO_USER_POOL_CLIENT_SECRET\"] = \"zxcvbnm1234567890\"\napp.config[\"AWS_COGNITO_REDIRECT_URL\"] = \"https://example.com/postlogin\"\napp.config[\"AWS_COGNITO_LOGOUT_URL\"] = \"https://example.com/postlogout\"\n\nauth = CognitoAuth(app)\n\n\n@app.route(\"/login\")\n@cognito_login\ndef login():\n    # A simple route that will redirect to the Cognito Hosted UI.\n    # No logic is required as the decorator handles the redirect to the Cognito\n    # hosted UI for the user to sign in.\n    # An optional \"state\" value can be set in the current session which will\n    # be passed and then used in the postlogin route (after the user has logged\n    # into the Cognito hosted UI); this could be used for dynamic redirects,\n    # for example, set `session['state'] = \"some_custom_value\"` before passing\n    # the user to this route\n    pass\n\n\n@app.route(\"/postlogin\")\n@cognito_login_callback\ndef postlogin():\n    # A route to handle the redirect after a user has logged in with Cognito.\n    # This route must be set as one of the User Pool client's Callback URLs in\n    # the Cognito console and also as the config value AWS_COGNITO_REDIRECT_URL.\n    # The decorator will store the validated access token in a HTTP only cookie\n    # and the user claims and info are stored in the Flask session:\n    # session[\"claims\"] and session[\"user_info\"].\n    # Do anything after the user has logged in here, e.g. a redirect or perform\n    # logic based on a custom `session['state']` value if that was set before\n    # login\n    return redirect(url_for(\"claims\"))\n\n\n@app.route(\"/claims\")\n@auth_required()\ndef claims():\n    # This route is protected by the Cognito authorisation. If the user is not\n    # logged in at this point or their token from Cognito is no longer valid\n    # a 401 Authentication Error is thrown, which can be caught by registering\n    # an `@app.error_handler(AuthorisationRequiredError)\n    # If their auth is valid, the current session will be shown including\n    # their claims and user_info extracted from the Cognito tokens.\n    return jsonify(session)\n\n\n@app.route(\"/admin\")\n@auth_required(groups=[\"admin\"])\ndef admin():\n    # This route will only be accessible to a user who is a member of all of\n    # groups specified in the \"groups\" argument on the auth_required decorator\n    # If they are not, a 401 Authentication Error is thrown, which can be caught\n    # by registering an `@app.error_handler(CognitoGroupRequiredError).\n    # If their auth is valid, the set of groups the user is a member of will be\n    # shown.\n\n    # Could also use: jsonify(session[\"user_info\"][\"cognito:groups\"])\n    return jsonify(session[\"claims\"][\"cognito:groups\"])\n\n\n@app.route(\"/edit\")\n@auth_required(groups=[\"admin\", \"editor\"], any_group=True)\ndef edit():\n    # This route will only be accessible to a user who is a member of any of\n    # groups specified in the \"groups\" argument on the auth_required decorator\n    # If they are not, a CognitoGroupRequiredError is raised which is handled\n    # below\n    return jsonify(session[\"claims\"][\"cognito:groups\"])\n\n\n@app.route(\"/logout\")\n@cognito_logout\ndef logout():\n    # Logout of the Cognito User pool and delete the cookies that were set\n    # on login.\n    # No logic is required here as it simply redirects to Cognito.\n    pass\n\n\n@app.route(\"/postlogout\")\ndef postlogout():\n    # This is the endpoint Cognito redirects to after a user has logged out,\n    # handle any logic here, like returning to the homepage.\n    # This route must be set as one of the User Pool client's Sign Out URLs.\n    return redirect(url_for(\"home\"))\n\n\nif __name__ == \"__main__\":\n    app.run()\n```\n\n\n## Development\n\nPrequisites:\n\n* [poetry](https://python-poetry.org/)\n* [pre-commit](https://pre-commit.com/)\n\nThe Makefile includes helpful commands setting a development environment, get started by installing the package into a new environment and setting up pre-commit by running `make install`. Run `make help` to see additional available commands (e.g. linting, testing and so on).\n\n* [Pytest](https://docs.pytest.org/en/6.2.x/) is used for testing the application (see `/tests`).\n* [MkDocs](https://www.mkdocs.org/) is used for generating docs and hosted with GH pages (see `/docs`).\n* Code is linted using [flake8](https://flake8.pycqa.org/en/latest/)\n* Code formatting is validated using [Black](https://github.com/psf/black)\n* [pre-commit](https://pre-commit.com/) is used to run these checks locally before files are pushed to git\n* The [Github Actions pipeline](.github/workflows/cicd.yml) runs these checks and tests\n* [Semantic-release](https://python-semantic-release.readthedocs.io/en/latest/) is used with [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) for automated releasing to PyPI\n\n\n## Contributing\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate and ensure 100% test coverage.\n\n\n## Credits\n\nThis work started as a fork of the unmaintained [Flask-AWSCognito](https://github.com/cgauge/Flask-AWSCognito) extension, revising the implementation following OAuth 2.1 recommendations, with inspiration from [flask-cognito-auth](https://github.com/shrivastava-v-ankit/flask-cognito-auth). Whilst there are serveral Cognito extensions available for Flask, none of those implement OAuth 2.1 recommendations, with some plugins not even actively maintained.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Flask extension that supports protecting routes with AWS Cognito following OAuth 2.1 best practices",
    "version": "1.5.0",
    "project_urls": {
        "Homepage": "https://github.com/mblackgeo/flask-cognito-lib",
        "Repository": "https://github.com/mblackgeo/flask-cognito-lib"
    },
    "split_keywords": [
        "flask",
        "extension",
        "oauth",
        "cognito"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "df62d0d8763eab7d717f72f6577f60162c311f428515036df8e928553d53c345",
                "md5": "b4b543656eaa0cd37103b2903d228cb4",
                "sha256": "526f19fdac63abe2ca3cb21f673f0fe1cc8ce94cb6394d0975a534f54f21bd1e"
            },
            "downloads": -1,
            "filename": "flask_cognito_lib-1.5.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b4b543656eaa0cd37103b2903d228cb4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 15044,
            "upload_time": "2023-07-12T09:39:52",
            "upload_time_iso_8601": "2023-07-12T09:39:52.732485Z",
            "url": "https://files.pythonhosted.org/packages/df/62/d0d8763eab7d717f72f6577f60162c311f428515036df8e928553d53c345/flask_cognito_lib-1.5.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "aa3356d5975d5d2be27442da80ef76bf9f8d696f0d78a072ad403a812816b311",
                "md5": "a2eabe55b1e872902d4341b0b92d2839",
                "sha256": "4c4137cef8434e263febb5e7624c5dd0b5b8134103ad1c4ceea149559c7656ad"
            },
            "downloads": -1,
            "filename": "flask_cognito_lib-1.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "a2eabe55b1e872902d4341b0b92d2839",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 14652,
            "upload_time": "2023-07-12T09:39:54",
            "upload_time_iso_8601": "2023-07-12T09:39:54.456059Z",
            "url": "https://files.pythonhosted.org/packages/aa/33/56d5975d5d2be27442da80ef76bf9f8d696f0d78a072ad403a812816b311/flask_cognito_lib-1.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-12 09:39:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mblackgeo",
    "github_project": "flask-cognito-lib",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "flask-cognito-lib"
}
        
Elapsed time: 0.09237s