Skip to main content

jwt authentication for aiohttp

Project description

aiohttp-clean-jwt

Простая аутентификация по JWT-токену для aiohttp

Источник вдохновения - aiohttp-jwt

К сожалению, оригинальная библиотека плохо документирована, перегружена малопонятным функционалом и уже несколько лет выглядит заброшенной.


Установка:

pip install aiohttp_clean_jwt

Пример использования:

from aiohttp import web
from aiohttp.web import Application, Request, Response
from aiohttp_clean_jwt import get_token, json_response, middleware_factory

JWT_SECRET = 'top_secret_word'
JWT_ALGORITHM = 'HS256'
JWT_EXP_DELTA_SECONDS = 360
JWT_AUTH_SCHEME = 'Bearer'


async def get_user_id(login: str, password: str) -> int:
    """ Проверка ID пользователя. В реальном приложении должна сходить в базу."""
    if login == 'vasya' and password == 'qwerty':
        return 12345


async def sign_in(request: Request) -> Response:
    """ Ручка авторизации """
    try:
        login = request.rel_url.query['login']
        password = request.rel_url.query['password']
    except KeyError:
        raise web.HTTPUnauthorized(reason='Missing credentials')

    user_id = await get_user_id(login=login, password=password)
    if user_id is not None:
        jwt_token = get_token({'user_id': str(user_id)},
                              expiration_s=JWT_EXP_DELTA_SECONDS,
                              algorithm=JWT_ALGORITHM,
                              secret=JWT_SECRET)

        return json_response({'token': jwt_token})
    else:
        raise web.HTTPUnauthorized(reason='Wrong credentials')

# Все ручки по умолчанию считаются приватными.
# Чтобы сделать ручку публичной, ее нужно явным образом перечислить в whitelist.
# Для доступа к приватным ручкам необходимо передавать полученный в /login токен через
# HTTP HEADER "Authorization: Bearer"


async def stub1(request: Request) -> Response:
    """ Приватная ручка 1"""
    user_id = request.rel_url.query['user_id']
    result = {'user_id': user_id, 'handler': 'stub1'}

    return json_response(result)


async def stub2(request: Request) -> Response:
    """ Приватная ручка 2"""
    user_id = request.rel_url.query['user_id']
    result = {'user_id': user_id, 'handler': 'stub2'}

    return json_response(result)


async def public(request: Request) -> Response:
    """ Публичная ручка"""
    result = {'user_id': 'anonymous', 'handler': 'public'}

    return json_response(result)


if __name__ == '__main__':
    app = Application(middlewares=middleware_factory(
        whitelist=['/login', '/public'],
        secret=JWT_SECRET,
        algorithm=JWT_ALGORITHM,
        auth_scheme=JWT_AUTH_SCHEME,
    ))

    app.add_routes([web.get('/login', sign_in), web.get('/public', public),
                    web.get('/stub1', stub1), web.get('/stub2', stub2)])

    web.run_app(app=app)

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_clean_jwt-0.1.1.tar.gz (16.2 kB view details)

Uploaded Source

Built Distribution

aiohttp_clean_jwt-0.1.1-py3-none-any.whl (16.6 kB view details)

Uploaded Python 3

File details

Details for the file aiohttp_clean_jwt-0.1.1.tar.gz.

File metadata

  • Download URL: aiohttp_clean_jwt-0.1.1.tar.gz
  • Upload date:
  • Size: 16.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.4

File hashes

Hashes for aiohttp_clean_jwt-0.1.1.tar.gz
Algorithm Hash digest
SHA256 a152ff8a1aed79e728e42629453dcf543f50f4376fe5f7418ff8a45ccb519549
MD5 fdf16df0acd1bb2ba72490aaffdfd754
BLAKE2b-256 0d14f64e4e846948131a6010a86ca0741aa1f4fb8de4ea43d27bcdd4c61491dd

See more details on using hashes here.

File details

Details for the file aiohttp_clean_jwt-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for aiohttp_clean_jwt-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2788dc98b5e0f0732e7d44fd90562ec33dc23a9501c6eb5db82bab45ed5d5679
MD5 11b2bb05cab4e449b5be2c3ccb216085
BLAKE2b-256 cf476a8f11eae7423ac71b200106361ca59f2dadbcc9af9d955b3d5ae899e703

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