Skip to main content

Helper Library to use the Microsoft Authentication Library (MSAL) with aiohttp

Project description

Async based MSAL helper for aiohttp - aiohttp_msal Python library

Authorization Code Flow Helper. Learn more about auth-code-flow at https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow

Async based OAuth using the Microsoft Authentication Library (MSAL) for Python.

Blocking MSAL functions are executed in the executor thread. Should be useful until such time as MSAL Python gets a true async version.

Tested with MSAL Python 1.21.0 onward - MSAL Python docs

AsycMSAL class

The AsyncMSAL class wraps the behavior in the following example app https://github.com/Azure-Samples/ms-identity-python-webapp/blob/master/app.py#L76

It is responsible to manage tokens & token refreshes and as a client to retrieve data using these tokens.

Acquire the token

Firstly you should get the tokens via OAuth

  1. initiate_auth_code_flow referernce

    The caller is expected to:

    1. somehow store this content, typically inside the current session of the server,
    2. guide the end user (i.e. resource owner) to visit that auth_uri, typically with a redirect
    3. and then relay this dict and subsequent auth response to acquire_token_by_auth_code_flow().

    Step 1 and part of Step 3 is stored by this class in the aiohttp_session

  2. acquire_token_by_auth_code_flow referernce

Use the token

Now you are free to make requests (typically from an aiohttp server)

session = await get_session(request)
aiomsal = AsyncMSAL(session)
async with aiomsal.get("https://graph.microsoft.com/v1.0/me") as res:
    res = await res.json()

Example web server

Complete routes can be found in routes.py

Start the login process

@ROUTES.get("/user/login")
async def user_login(request: web.Request) -> web.Response:
    """Redirect to MS login page."""
    session = await new_session(request)

    redir = AsyncMSAL(session).build_auth_code_flow(
        redirect_uri=get_route(request, URI_USER_AUTHORIZED)
    )

    return web.HTTPFound(redir)

Acquire the token after being redirected back to the server

@ROUTES.post(URI_USER_AUTHORIZED)
async def user_authorized(request: web.Request) -> web.Response:
    """Complete the auth code flow."""
    session = await get_session(request)
    auth_response = dict(await request.post())

    aiomsal = AsyncMSAL(session)
    await aiomsal.async_acquire_token_by_auth_code_flow(auth_response)

Helper methods

  • @ROUTES.get("/user/photo")

    Serve the user's photo from their Microsoft profile

  • get_user_info

    Get the user's email and display name from MS Graph

  • get_manager_info

    Get the user's manager info from MS Graph

Redis tools to retrieve session tokens

from aiohttp_msal import ENV, AsyncMSAL
from aiohttp_msal.redis_tools import get_session

def main()
    # Uses the redis.asyncio driver to retrieve the current token
    # Will update the token_cache if a RefreshToken was used
    ses = asyncio.run(get_session(MYEMAIL))
    client = GraphClient(ses.get_token)
    # ...
    # use the Graphclient

Development

uv sync --all-extras
uv tool install ruff
uv tool install prek
prek install  # add pre-commit hooks

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

aiohttp_msal-1.1.0.tar.gz (14.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

aiohttp_msal-1.1.0-py3-none-any.whl (17.7 kB view details)

Uploaded Python 3

File details

Details for the file aiohttp_msal-1.1.0.tar.gz.

File metadata

  • Download URL: aiohttp_msal-1.1.0.tar.gz
  • Upload date:
  • Size: 14.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for aiohttp_msal-1.1.0.tar.gz
Algorithm Hash digest
SHA256 a61bef4dd1ed0bd5aeca32c32d5be4edabedf44c025ba611d84679c4b7203128
MD5 3b7a7deb1c44709a755245051aaa5682
BLAKE2b-256 f8529f93d58f0883e02bc022a3ccaad935edac1a16002f585c32b13062b4d098

See more details on using hashes here.

File details

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

File metadata

  • Download URL: aiohttp_msal-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 17.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.10.2 {"installer":{"name":"uv","version":"0.10.2","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for aiohttp_msal-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7ea6ace0c7dfa49091bc5b28e3cec975d01f48abf2c4d6250a51c1abe8a1b16c
MD5 eee5da1b809e7718d448c520029e725a
BLAKE2b-256 2f718c1bb613e1928ec439145b5aeaae3c676e8913c6facdbaa177d16993d470

See more details on using hashes here.

Supported by

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