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

69 lines
2.5 KiB
Python

from typing import List
from fastapi import Depends, HTTPException, Request, WebSocket, status
from .exceptions import ForbiddenException
from .manager import AuthManager
from .models import User
async def get_auth_manager(request: Request) -> AuthManager:
"""Dependency provider for auth manager"""
if hasattr(request.app.state, "auth_manager"):
return request.app.state.auth_manager
# We can remove this part since it depends on the global in deps.py
# It's better to throw the error directly
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Auth manager not initialized")
def get_ws_auth_manager(websocket: WebSocket) -> AuthManager:
"""Get the auth manager from app state for WebSocket connections."""
if hasattr(websocket.app.state, "auth_manager"):
return websocket.app.state.auth_manager
# Similar to above, remove the global reference
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Authentication system not initialized"
)
def get_current_user(request: Request) -> User:
"""Get the current authenticated user."""
if hasattr(request.state, "user"):
return request.state.user
# Fall back to anonymous user if middleware didn't set user
# This should generally not happen
return User(id="anonymous", name="Anonymous User")
def require_authenticated(user: User = Depends(get_current_user)) -> User:
"""Require that the user is authenticated (not anonymous)."""
if user.id == "anonymous":
raise HTTPException(status_code=401, detail="Authentication required")
return user
def require_roles(required_roles: List[str]):
"""
Dependency factory to require specific roles.
Example:
@router.get("/admin-only")
async def admin_endpoint(user: User = Depends(require_roles(["admin"]))):
# Only users with admin role will get here
return {"message": "Welcome, admin!"}
"""
def _require_roles(user: User = Depends(require_authenticated)) -> User:
"""Require that the user has at least one of the specified roles."""
user_roles = set(user.roles or [])
if not any(role in user_roles for role in required_roles):
raise ForbiddenException(f"This endpoint requires one of these roles: {', '.join(required_roles)}")
return user
return _require_roles
def require_admin(user: User = Depends(require_roles(["admin"]))) -> User:
"""Convenience dependency to require admin role."""
return user