Code Monkey home page Code Monkey logo

aiohttp-tokenauth's Introduction

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"}

aiohttp-tokenauth's People

Contributors

madnesspie avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.