Skip to main content

Handle OAuth2 authentication for REST APIs

pypi version Build status Coverage Code style: black Number of tests Number of downloads

As expected by the HTTP specification, token is extracted from Authorization header and must be prefixed with Bearer .

Token will then be validated and in case it is valid, you will be able to access the raw token (as string) and the decoded token body (as dictionary).

Starlette

Provides a Starlette authentication backend: layabauth.starlette.OAuth2IdTokenBackend.

3 arguments are required:

  • The JWKs URI as defined in .well-known.
  • Azure Active Directory: https://sts.windows.net/common/discovery/keys
  • Microsoft Identity Platform: https://sts.windows.net/common/discovery/keys

Below is a sample Starlette application with an endpoint requesting a Microsoft issued OAuth2 token.

import starlette.applications
from starlette.authentication import SimpleUser, requires
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.responses import PlainTextResponse

import layabauth.starlette

backend = layabauth.starlette.OAuth2IdTokenBackend(
    jwks_uri="https://sts.windows.net/common/discovery/keys",
    create_user=lambda token, token_body: SimpleUser(token_body["name"]),
    scopes=lambda token, token_body: token_body["scopes"]
)
app = starlette.applications.Starlette(middleware=[Middleware(AuthenticationMiddleware, backend=backend)])

@app.route("/my_endpoint")
@requires('my_scope')
async def my_endpoint(request):
    return PlainTextResponse(request.user.display_name)

Flask

Provides a decorator layabauth.flask.requires_authentication to ensure that, in a context of a Flask application, a valid OAuth2 token was received.

The JWKs URI as defined in .well-known is the only required argument.

  • Azure Active Directory: https://sts.windows.net/common/discovery/keys
  • Microsoft Identity Platform: https://sts.windows.net/common/discovery/keys

If validation fails, an werkzeug.exceptions.Unauthorized exception is raised. Otherwise token is stored in flask.g.token and decoded token body is stored in flask.g.token_body.

Decorator works fine on flask-restplus methods as well.

Below is a sample Flask application with an endpoint requesting a Microsoft issued OAuth2 token.

import flask
import layabauth.flask

app = flask.Flask(__name__)

@app.route("/my_endpoint")
@layabauth.flask.requires_authentication("https://sts.windows.net/common/discovery/keys")
def my_endpoint():
    # Optional, ensure that the appropriates scopes are provided
    layabauth.flask.requires_scopes(lambda token, token_body: token_body["scopes"], "my_scope")
    # Return the content of the name entry within the decoded token body.
    return flask.Response(flask.g.token_body["name"])

app.run()

OpenAPI

You can generate OpenAPI 2.0 security definition thanks to layabauth.authorizations.

You can generate OpenAPI 2.0 method security thanks to layabauth.method_authorizations

Testing

Authentication can be mocked using layabauth.testing.auth_mock pytest fixture.

token_body pytest fixture returning the decoded token body used in tests must be provided. jwks_uri pytest fixture returning the jwks_uri used in tests must be provided.

from layabauth.testing import *


@pytest.fixture
def jwks_uri():
    return "https://sts.windows.net/common/discovery/keys"


@pytest.fixture
def token_body():
    return {"name": "TEST@email.com", "scopes": ["my_scope"]}


def test_authentication(auth_mock, client):
    response = client.get("/my_endpoint", headers={"Authentication": "Bearer mocked_token"})
    assert response.text == "TEST@email.com"

How to install

  1. python 3.7+ must be installed
  2. Use pip to install module:
python -m pip install layabauth

Metadata

Release files for layabauth 7.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for layabauth 7.0.0
File Size Uploaded
layabauth-7.0.0.tar.gz 15.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for layabauth 7.0.0
File Interpreter ABI Platform
layabauth-7.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 23.7 kB

Release files / layabauth-7.0.0.tar.gz

Download URL layabauth-7.0.0.tar.gz
Size 15.2 kB
Tags Source
SHA-256 checksum
How to use checksums
904ee28d3b9362e9344378feb050f05bcf272eb675adcb9ebeaa218db9367e2b
BLAKE2b-256 checksum
How to use checksums
dd4592b65092baf91541a2635264e19a97e321e6b100ecd085932fc68f192f7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.8.16

Release files / layabauth-7.0.0-py3-none-any.whl

Download URL layabauth-7.0.0-py3-none-any.whl
Size 8.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e2fb33ae2d7da1c32e0f7f68bee2091d2a1039d2b2d0b8e33df360558aa2dd9
BLAKE2b-256 checksum
How to use checksums
d3d38ad56cf5086f727d413e5a21f0440664570a573a08b15d858aa325a13a5c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.8.16

Release history Release notifications | RSS feed

This release

7.0.0 This release

2 release files

6.0.0

2 release files

5.1.0

2 release files

5.0.1

2 release files

5.0.0

2 release files

4.0.1

2 release files

4.0.0

2 release files

3.2.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page