Skip to main content

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)

Metadata

Release files for aiohttp-clean-jwt 0.1.1

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

Source distribution (sdist)

Source distribution for aiohttp-clean-jwt 0.1.1
File Size Uploaded Provenance Actions
aiohttp_clean_jwt-0.1.1.tar.gz 16.2 kB Without provenance Details for aiohttp_clean_jwt-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiohttp-clean-jwt 0.1.1
File Interpreter ABI Platform Actions
aiohttp_clean_jwt-0.1.1-py3-none-any.whl Python 3 none any Details for aiohttp_clean_jwt-0.1.1-py3-none-any.whl

Total release size: 32.8 kB

Release files / aiohttp_clean_jwt-0.1.1.tar.gz

Download URL aiohttp_clean_jwt-0.1.1.tar.gz
Size 16.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a152ff8a1aed79e728e42629453dcf543f50f4376fe5f7418ff8a45ccb519549
BLAKE2b-256 checksum
How to use checksums
0d14f64e4e846948131a6010a86ca0741aa1f4fb8de4ea43d27bcdd4c61491dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.4

Release files / aiohttp_clean_jwt-0.1.1-py3-none-any.whl

Download URL aiohttp_clean_jwt-0.1.1-py3-none-any.whl
Size 16.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2788dc98b5e0f0732e7d44fd90562ec33dc23a9501c6eb5db82bab45ed5d5679
BLAKE2b-256 checksum
How to use checksums
cf476a8f11eae7423ac71b200106361ca59f2dadbcc9af9d955b3d5ae899e703
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.1 CPython/3.10.4

Security for aiohttp-clean-jwt 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

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