MCPcopy Create free account
hub / github.com/aio-libs/aiohttp / handle_basic_auth

Method handle_basic_auth

examples/basic_auth_middleware.py:62–98  ·  view source on GitHub ↗

Handle basic auth validation.

(self, request: web.Request)

Source from the content-addressed store, hash-verified

60 """Test server for basic auth endpoints."""
61
62 async def handle_basic_auth(self, request: web.Request) -> web.Response:
63 """Handle basic auth validation."""
64 # Get expected credentials from path
65 expected_user = request.match_info["user"]
66 expected_pass = request.match_info["pass"]
67
68 # Check if Authorization header is present
69 auth_header = request.headers.get(hdrs.AUTHORIZATION, "")
70
71 if not auth_header.startswith("Basic "):
72 return web.Response(
73 status=401,
74 text="Unauthorized",
75 headers={hdrs.WWW_AUTHENTICATE: 'Basic realm="test"'},
76 )
77
78 # Decode the credentials
79 encoded_creds = auth_header[6:] # Remove "Basic "
80 try:
81 decoded = base64.b64decode(encoded_creds).decode()
82 username, password = decoded.split(":", 1)
83 except (ValueError, binascii.Error):
84 return web.Response(
85 status=401,
86 text="Invalid credentials format",
87 headers={hdrs.WWW_AUTHENTICATE: 'Basic realm="test"'},
88 )
89
90 # Validate credentials
91 if username != expected_user or password != expected_pass:
92 return web.Response(
93 status=401,
94 text="Invalid username or password",
95 headers={hdrs.WWW_AUTHENTICATE: 'Basic realm="test"'},
96 )
97
98 return web.json_response({"authenticated": True, "user": username})
99
100 async def handle_protected_resource(self, request: web.Request) -> web.Response:
101 """A protected resource that requires any valid auth."""

Callers

nothing calls this directly

Calls 2

getMethod · 0.45
decodeMethod · 0.45

Tested by

no test coverage detected