Victor Dibia fe1feb3906
Enable Auth in AGS (#5928)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?


https://github.com/user-attachments/assets/b649053b-c377-40c7-aa51-ee64af766fc2

<img width="100%" alt="image"
src="https://github.com/user-attachments/assets/03ba1df5-c9a2-4734-b6a2-0eb97ec0b0e0"
/>


## Authentication

This PR implements an experimental authentication feature to enable
personalized experiences (multiple users). Currently, only GitHub
authentication is supported. You can extend the base authentication
class to add support for other authentication methods.

By default authenticatio is disabled and only enabled when you pass in
the `--auth-config` argument when running the application.

### Enable GitHub Authentication

To enable GitHub authentication, create a `auth.yaml` file in your app
directory:

```yaml
type: github
jwt_secret: "your-secret-key"
token_expiry_minutes: 60
github:
  client_id: "your-github-client-id"
  client_secret: "your-github-client-secret"
  callback_url: "http://localhost:8081/api/auth/callback"
  scopes: ["user:email"]
```

Please see the documentation on [GitHub
OAuth](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authenticating-to-the-rest-api-with-an-oauth-app)
for more details on obtaining the `client_id` and `client_secret`.

To pass in this configuration you can use the `--auth-config` argument
when running the application:

```bash
autogenstudio ui --auth-config /path/to/auth.yaml
```

Or set the environment variable:

```bash
export AUTOGENSTUDIO_AUTH_CONFIG="/path/to/auth.yaml"
```

```{note}
- Authentication is currently experimental and may change in future releases
- User data is stored in your configured database
- When enabled, all API endpoints require authentication except for the authentication endpoints
- WebSocket connections require the token to be passed as a query parameter (`?token=your-jwt-token`)

```

## Related issue number

<!-- For example: "Closes #1234" -->
Closes #4350  

## Checks

- [ ] I've included any doc changes needed for
<https://microsoft.github.io/autogen/>. See
<https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2025-03-14 15:02:05 -07:00

120 lines
4.1 KiB
Python

import json
import re
from fastapi import Request, Response, WebSocket
from loguru import logger
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.status import HTTP_401_UNAUTHORIZED
from .exceptions import AuthException
from .manager import AuthManager
class AuthMiddleware(BaseHTTPMiddleware):
"""
Middleware for handling authentication for all routes.
"""
def __init__(self, app, auth_manager: AuthManager):
super().__init__(app)
self.auth_manager = auth_manager
async def dispatch(self, request: Request, call_next):
"""Process each request, authenticating as needed."""
# Skip auth for OPTIONS requests (CORS preflight)
if request.method == "OPTIONS":
return await call_next(request)
path = request.url.path
if (
path == "/"
or path == "/login"
or path == "/callback"
or path == "/images"
or path.startswith("/page-data/")
or path in self.auth_manager.config.exclude_paths
or re.match(r"/[^/]+\.(js|css|png|ico|svg|jpg|webmanifest|json)$", path)
or re.match(r".*\.(js\.map|svg)$", path)
):
return await call_next(request)
# Skip auth if disabled
if self.auth_manager.config.type == "none":
request.state.user = await self.auth_manager.authenticate_request(request)
return await call_next(request)
# WebSocket handling (special case)
if request.url.path.startswith("/api/ws"):
# For WebSockets, we'll add auth in the WebSocket accept handler
# Just pass through here
return await call_next(request)
# Handle authentication for all other requests
try:
user = await self.auth_manager.authenticate_request(request)
# Add user to request state for use in route handlers
request.state.user = user
return await call_next(request)
except AuthException as e:
# Handle authentication errors
return Response(
status_code=HTTP_401_UNAUTHORIZED,
content=json.dumps({"status": False, "detail": e.detail}),
media_type="application/json",
headers=e.headers or {},
)
except Exception as e:
# Log unexpected errors
logger.error(f"Unexpected error in auth middleware: {str(e)}")
return Response(
status_code=HTTP_401_UNAUTHORIZED,
content=json.dumps({"status": False, "detail": "Authentication failed"}),
media_type="application/json",
)
class WebSocketAuthMiddleware:
"""
Helper for authenticating WebSocket connections.
Not a middleware in the traditional sense - used in WebSocket endpoint.
"""
def __init__(self, auth_manager: AuthManager):
self.auth_manager = auth_manager
async def authenticate(self, websocket: WebSocket) -> bool:
"""
Authenticate a WebSocket connection.
Returns True if authenticated, False otherwise.
"""
if self.auth_manager.config.type == "none":
return True
try:
# Extract token from query params or cookies
token = None
if "token" in websocket.query_params:
token = websocket.query_params["token"]
elif "authorization" in websocket.headers:
auth_header = websocket.headers["authorization"]
if auth_header.startswith("Bearer "):
token = auth_header.replace("Bearer ", "")
if not token:
logger.warning("No token found for WebSocket connection")
return False
# Validate token
valid = self.auth_manager.is_valid_token(token)
if not valid:
logger.warning("Invalid token for WebSocket connection")
return False
return True
except Exception as e:
logger.error(f"WebSocket auth error: {str(e)}")
return False