def basic_auth_middleware_factory(app: web.Application, handler: Any) -> Callable:
"""Authentication.
Uses HTTP basic auth to check that requests are including the required
username and password.
"""
async def middleware_handler(request: web.Request) -> web.Response:
ok = False
auth_token = request.headers.get('Authorization')
if auth_token and auth_token.startswith('Basic '):
auth_token = auth_token[6:]
try:
auth_bytes = base64.b64decode(auth_token) # type: Optional[bytes]
except binascii.Error:
auth_bytes = None
if auth_bytes:
auth_str = auth_bytes.decode('utf-8', errors='ignore')
if ':' in auth_str:
username, password = auth_str.split(':', 1)
if username == app['username'] and password == app['password']:
ok = True
if not ok:
log.msg('Unauthorized request: %s' % request, 'WEBMGMT')
raise errors.MissingLogin('Unauthorized')
return await handler(request)
return middleware_handler
# noinspection PyUnusedLocal
评论列表
文章目录