Implementation:Microsoft Autogen Studio Auth Context
| Metadata | Value |
|---|---|
| Sources | Microsoft_Autogen |
| Domains | Authentication, React Context, OAuth Integration, Frontend Security |
| Last Updated | 2026-02-11 17:00 GMT |
Overview
Description
The AuthContext is a React Context provider that manages authentication state and user sessions in the AutoGen Studio frontend. It implements OAuth-based authentication with popup window support, handles token management via localStorage, and provides security validation for message origins and user data. The context supports multiple authentication modes (none, OAuth), automatically loads user state on mount, and provides hooks for login, logout, and callback handling. It includes comprehensive security measures including URL sanitization, message origin validation, and user object structure verification to protect against XSS and injection attacks.
Usage
Wrap the application root with AuthProvider to enable authentication throughout the component tree. Components access authentication state and methods via the useAuth hook. The context automatically:
- Checks authentication type on mount (none vs OAuth)
- Loads user from token if present
- Handles popup-based OAuth flows with message passing
- Manages token storage in localStorage
- Validates message origins and user data structure
- Provides SSR-safe defaults for Gatsby static rendering
- Redirects appropriately after login/logout
Code Reference
Source Location
Repository: https://github.com/microsoft/autogen
File: python/packages/autogen-studio/frontend/src/auth/context.tsx
Lines: 1-217
Signature
// Context Type
interface AuthContextType {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
authType: string;
login: () => Promise<string>;
logout: () => void;
handleAuthCallback: (code: string, state?: string) => Promise<void>;
}
// Provider Component
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
// Implementation
};
// Hook
export const useAuth = (): AuthContextType => {
// Returns context or SSR-safe defaults
};
// User Type (from auth API)
interface User {
id: string;
name: string;
avatar_url?: string;
}Import
import { AuthProvider, useAuth } from "../auth/context";
import { User } from "../auth/api";I/O Contract
Inputs
AuthProvider Props
| Prop | Type | Description | Required |
|---|---|---|---|
| children | React.ReactNode | Child components to render within authentication context | Yes |
handleAuthCallback Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
| code | string | OAuth authorization code from provider | Yes |
| state | string | OAuth state parameter for CSRF protection | No |
localStorage
| Key | Type | Description |
|---|---|---|
| auth_token | string | JWT or session token from authentication server |
Message Events (from popup window)
| Field | Type | Description |
|---|---|---|
| type | string | Message type: "auth-success" or "auth-error" |
| token | string | Authentication token (for auth-success) |
| user | User | User object with id, name, and optional avatar_url (for auth-success) |
| error | string | Error message (for auth-error) |
Outputs
useAuth Hook Return Value
| Property | Type | Description |
|---|---|---|
| user | User or null | Current authenticated user or null if not authenticated |
| isAuthenticated | boolean | Whether user is currently authenticated |
| isLoading | boolean | Whether authentication state is being loaded |
| authType | string | Authentication type: "none" (disabled) or OAuth provider type |
| login | () => Promise<string> | Function to initiate login, returns login URL |
| logout | () => void | Function to log out user and clear session |
| handleAuthCallback | (code: string, state?: string) => Promise<void> | Function to handle OAuth callback |
Side Effects
- Stores/removes tokens in localStorage
- Displays Ant Design messages for success/error states
- Navigates to home ("/") after successful login
- Navigates to login ("/login") after logout
- Validates message origins against window.location.origin
- Sanitizes URLs and user data to prevent XSS
Usage Examples
Basic Provider Setup
import React from "react";
import { AuthProvider } from "./auth/context";
import App from "./App";
const Root: React.FC = () => {
return (
<AuthProvider>
<App />
</AuthProvider>
);
};
export default Root;Using Authentication in Components
import React from "react";
import { useAuth } from "../auth/context";
import { Button, Avatar, Spin } from "antd";
const Header: React.FC = () => {
const { user, isAuthenticated, isLoading, login, logout } = useAuth();
if (isLoading) {
return <Spin />;
}
return (
<div className="header">
{isAuthenticated ? (
<div>
<Avatar src={user?.avatar_url}>{user?.name[0]}</Avatar>
<span>{user?.name}</span>
<Button onClick={logout}>Logout</Button>
</div>
) : (
<Button onClick={login}>Login</Button>
)}
</div>
);
};
export default Header;Protected Route Component
import React, { useEffect } from "react";
import { useAuth } from "../auth/context";
import { navigate } from "gatsby";
interface ProtectedRouteProps {
children: React.ReactNode;
}
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
const { isAuthenticated, isLoading, authType } = useAuth();
useEffect(() => {
if (!isLoading && !isAuthenticated && authType !== "none") {
navigate("/login");
}
}, [isAuthenticated, isLoading, authType]);
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated && authType !== "none") {
return null;
}
return <>{children}</>;
};
export default ProtectedRoute;Login Page with Popup
import React, { useState } from "react";
import { useAuth } from "../auth/context";
import { Button, Card } from "antd";
const LoginPage: React.FC = () => {
const { login, authType } = useAuth();
const [isLoggingIn, setIsLoggingIn] = useState(false);
const handleLogin = async () => {
setIsLoggingIn(true);
try {
const loginUrl = await login();
if (loginUrl) {
// Open popup window for OAuth
const width = 600;
const height = 700;
const left = window.screen.width / 2 - width / 2;
const top = window.screen.height / 2 - height / 2;
window.open(
loginUrl,
"OAuth Login",
`width=${width},height=${height},left=${left},top=${top}`
);
}
} catch (error) {
console.error("Login failed:", error);
} finally {
setIsLoggingIn(false);
}
};
if (authType === "none") {
// No authentication required
return <div>Authentication disabled</div>;
}
return (
<Card title="Login to AutoGen Studio">
<Button
type="primary"
onClick={handleLogin}
loading={isLoggingIn}
>
Login with OAuth
</Button>
</Card>
);
};
export default LoginPage;OAuth Callback Handler
import React, { useEffect } from "react";
import { useAuth } from "../auth/context";
import { Spin } from "antd";
interface CallbackPageProps {
location: {
search: string;
};
}
const CallbackPage: React.FC<CallbackPageProps> = ({ location }) => {
const { handleAuthCallback } = useAuth();
useEffect(() => {
const params = new URLSearchParams(location.search);
const code = params.get("code");
const state = params.get("state");
if (code) {
handleAuthCallback(code, state || undefined);
}
}, [location.search, handleAuthCallback]);
return (
<div style={{ textAlign: "center", padding: "50px" }}>
<Spin size="large" />
<p>Completing authentication...</p>
</div>
);
};
export default CallbackPage;Displaying User Profile
import React from "react";
import { useAuth } from "../auth/context";
import { Card, Avatar, Typography, Button } from "antd";
const { Title, Text } = Typography;
const ProfilePage: React.FC = () => {
const { user, logout } = useAuth();
if (!user) {
return <div>Not authenticated</div>;
}
return (
<Card>
<div style={{ textAlign: "center" }}>
<Avatar size={64} src={user.avatar_url}>
{user.name[0]}
</Avatar>
<Title level={3}>{user.name}</Title>
<Text type="secondary">{user.id}</Text>
<div style={{ marginTop: "20px" }}>
<Button danger onClick={logout}>
Logout
</Button>
</div>
</div>
</Card>
);
};
export default ProfilePage;Conditional Rendering Based on Auth
import React from "react";
import { useAuth } from "../auth/context";
const Dashboard: React.FC = () => {
const { isAuthenticated, user, authType } = useAuth();
return (
<div>
{authType === "none" ? (
<div>
<h1>Welcome, Guest User!</h1>
<p>Authentication is disabled for this instance.</p>
</div>
) : isAuthenticated ? (
<div>
<h1>Welcome back, {user?.name}!</h1>
<p>You have access to all features.</p>
</div>
) : (
<div>
<h1>Please log in</h1>
<p>You need to authenticate to access this content.</p>
</div>
)}
</div>
);
};
export default Dashboard;Related Pages
- Studio Auth API - Backend authentication endpoints
- Studio Security Utils - URL sanitization and validation functions
- OAuth Integration - OAuth provider configuration
- Studio Frontend - Main Gatsby application structure
- Token Management - JWT token handling and validation
- Protected Routes - Route protection patterns