Skip to main content

Simple way to add token auth level in your aiohttp app

Project description

aiohttp-tokenauth

Aiohttp simple token auth middleware that can check any token that assign to user or group of users in database or some another place.

Installation

pip install aiohttp_tokenauth

Documentation

Basic usage

First of all, let's create a simple app.

# Full text in example/simple_app.py
from aiohttp import web
from aiohttp_tokenauth import token_auth_middleware


async def example_resource(request):
    return web.json_response(request['user'])


async def init():

    async def user_loader(token: str):
        """Checks that token is valid

        It's the callback that will get the token from "Authorization" header.
        It can check that token is exist in a database or some another place.

        Args:
            token (str): A token from "Authorization" http header.

        Returns:
            Dict or something else. If the callback returns None then
            the aiohttp.web.HTTPForbidden will be raised.
        """
        user = None
        if token == 'fake-token':
            user = {'uuid': 'fake-uuid'}
        return user

    app = web.Application(middlewares=[token_auth_middleware(user_loader)])
    app.router.add_get('/', example_resource)
    return app


if __name__ == '__main__':
    web.run_app(init())

Then, run the aiohttp app.

$ python example/simple_app.py
======== Running on http://0.0.0.0:8080 ========
(Press CTRL+C to quit)

Now try to get access to url with token in "Authorization" header.

$ curl -H 'Authorization: Bearer fake-token' http://0.0.0.0:8080
{"uuid": "fake-uuid"}

And result without token.

$ curl http://0.0.0.0:8080
401: Missing authorization header

Ignoring routes and http methods

You can ignore specific routes, app the paths to "exclude_routes".

app = web.Application(middlewares=[
    token_auth_middleware(
        user_loader=user_loader,
        # You can use regular expressions here
        exclude_routes=('/exclude', r'/exclude/\w+/info'),
        exclude_methods=('POST',),
    ),
])

Change auth scheme

For changing the scheme (prefix in "Authorization" header) use auth_scheme argument.

app = web.Application(middlewares=[
    token_auth_middleware(
        user_loader=user_loader,
        auth_scheme='Token',
    ),
])

Now such request is valid:

$ curl -H 'Authorization: Token fake-token' http://0.0.0.0:8080
{"uuid": "fake-uuid"}

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

aiohttp_tokenauth-0.0.2-py3-none-any.whl (16.3 kB view details)

Uploaded Python 3

File details

Details for the file aiohttp_tokenauth-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: aiohttp_tokenauth-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 16.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.22.0 setuptools/42.0.2 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.8.1

File hashes

Hashes for aiohttp_tokenauth-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 def68d3618e084cfb1f67c3f81042365b6eeee12f80dfe69ded7253ce397d052
MD5 8e5fac70b7ac4aaa57a3b3386fbbcd96
BLAKE2b-256 dad5d8ea93c585735352d3c320e6383cdedf3fbd336bf87f76f5fea69862cca0

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