Test server for basic auth endpoints.
| 57 | |
| 58 | |
| 59 | class TestServer: |
| 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.""" |
| 102 | auth_header = request.headers.get(hdrs.AUTHORIZATION, "") |
| 103 | |
| 104 | if not auth_header.startswith("Basic "): |
| 105 | return web.Response( |
| 106 | status=401, |
| 107 | text="Authentication required", |
| 108 | headers={hdrs.WWW_AUTHENTICATE: 'Basic realm="protected"'}, |
| 109 | ) |
| 110 | |
| 111 | return web.json_response( |
| 112 | { |
| 113 | "message": "Access granted to protected resource", |
| 114 | "auth_provided": True, |
| 115 | } |
| 116 | ) |