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

107 lines
2.4 KiB
TypeScript

import { getServerUrl } from "../components/utils/utils";
export interface User {
id: string;
name: string;
email?: string;
avatar_url?: string;
provider?: string;
roles?: string[];
}
export class AuthAPI {
private getBaseUrl(): string {
return getServerUrl();
}
private getHeaders(token?: string): HeadersInit {
const headers: HeadersInit = {
"Content-Type": "application/json",
};
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
return headers;
}
async getLoginUrl(): Promise<string> {
try {
const response = await fetch(`${this.getBaseUrl()}/auth/login-url`, {
headers: this.getHeaders(),
});
const data = await response.json();
if (!data.login_url) {
throw new Error("Failed to get login URL");
}
return data.login_url;
} catch (error) {
console.error("Error getting login URL:", error);
throw error;
}
}
async handleCallback(
code: string,
state?: string
): Promise<{ token: string; user: User }> {
try {
const response = await fetch(
`${this.getBaseUrl()}/auth/callback-handler`,
{
method: "POST",
headers: this.getHeaders(),
body: JSON.stringify({ code, state }),
}
);
const data = await response.json();
if (!data.token || !data.user) {
throw new Error("Authentication failed");
}
return data;
} catch (error) {
console.error("Error handling auth callback:", error);
throw error;
}
}
async getCurrentUser(token: string): Promise<User> {
try {
const response = await fetch(`${this.getBaseUrl()}/auth/me`, {
headers: this.getHeaders(token),
});
if (response.status === 401) {
throw new Error("Unauthorized");
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error getting current user:", error);
throw error;
}
}
async checkAuthType(): Promise<{ type: string }> {
try {
const response = await fetch(`${this.getBaseUrl()}/auth/type`, {
headers: this.getHeaders(),
});
const data = await response.json();
return data;
} catch (error) {
console.error("Error checking auth type:", error);
return { type: "none" }; // Default to no auth
}
}
}
export const authAPI = new AuthAPI();