HTTP basic authentication middleware for aiohttp 3.0+. Inspired by Flask-BasicAuth.
- Python >= 3.5.3
- aiohttp >= 3.0
pip install aiohttp_basicauth
from aiohttp import web
from aiohttp_basicauth import BasicAuthMiddleware
auth = BasicAuthMiddleware(username='user', password='password')
app = web.Application(middlewares=[auth])
web.run_app(app, host='127.0.0.1', port=80)
from aiohttp import web
from aiohttp_basicauth import BasicAuthMiddleware
auth = BasicAuthMiddleware(username='user', password='password', force=False)
async def public_view(request):
return web.Response(text='Public view')
@auth.required
async def secret_view(request):
return web.Response(text='Secret view')
app = web.Application(middlewares=[auth])
app.router.add_route('GET', '/public', public_view)
app.router.add_route('GET', '/secret', secret_view)
web.run_app(app, host='127.0.0.1', port=80)
You can override check_credentials
method to implement more complex user verification logic:
from aiohttp import web
from aiohttp_basicauth import BasicAuthMiddleware
class CustomBasicAuth(BasicAuthMiddleware):
async def check_credentials(self, username, password, request):
# here, for example, you can search user in the database by passed `username` and `password`, etc.
return username == 'user' and password == 'password'
auth = CustomBasicAuth()
app = web.Application(middlewares=[auth])
web.run_app(app, host='127.0.0.1', port=80)