Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Microsoft Autogen Studio Auth Routes

From Leeroopedia
Revision as of 11:33, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Microsoft_Autogen_Studio_Auth_Routes.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Metadata
Sources python/packages/autogen-studio/autogenstudio/web/auth/authroutes.py
Domains Authentication, OAuth, REST_API, FastAPI
Last Updated 2026-02-11 17:00 GMT

Overview

Description

The Studio Auth Routes module implements the FastAPI router for authentication endpoints in AutoGen Studio. It provides REST API routes for OAuth authentication flows, user session management, and authentication configuration queries. The module handles OAuth callbacks with a hybrid approach supporting both popup-based and redirect-based authentication flows.

The router integrates with the AuthManager to provide a complete authentication solution, including login URL generation, OAuth callback processing, token exchange, and user information retrieval. It uses dependency injection for accessing the auth manager and current user context.

Usage

This module provides five primary endpoints:

  • GET /login-url - Returns OAuth login URL for frontend
  • GET /callback - Handles OAuth provider redirects with popup/redirect support
  • POST /callback-handler - Exchanges auth codes for tokens (frontend-initiated)
  • GET /me - Returns current authenticated user information
  • GET /type - Returns authentication configuration type

Code Reference

Source Location

Repository: https://github.com/microsoft/autogen
File Path: python/packages/autogen-studio/autogenstudio/web/auth/authroutes.py
Lines: 194

Router and Dependencies

from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, Response

router = APIRouter()

def get_auth_manager(request: Request) -> AuthManager:
    """Get the auth manager from app state."""
    if not hasattr(request.app.state, "auth_manager"):
        raise HTTPException(status_code=500, detail="Authentication system not initialized")
    return request.app.state.auth_manager

def get_current_user(request: Request) -> User:
    """Get the current authenticated user."""
    if hasattr(request.state, "user"):
        return request.state.user
    logger.warning("User not found in request state")
    return User(id="anonymous", name="Anonymous User")

Import Statement

from autogenstudio.web.auth.authroutes import router

# Include in FastAPI app:
app.include_router(router, prefix="/api/auth", tags=["auth"])

API Endpoints

GET /login-url

Purpose: Generate OAuth login URL for frontend to redirect to

@router.get("/login-url")
async def get_login_url(auth_manager: AuthManager = Depends(get_auth_manager))
Response Description
{"login_url": "https://..."} OAuth provider login URL with state parameter

Status Codes:

  • 200 - Success
  • 500 - Failed to generate login URL

GET /callback

Purpose: OAuth callback handler for provider redirects

@router.get("/callback")
async def oauth_callback(
    request: Request,
    code: Optional[str] = None,
    state: Optional[str] = None,
    error: Optional[str] = None,
    auth_manager: AuthManager = Depends(get_auth_manager)
)
Parameter Type Description
code str (optional) OAuth authorization code from provider
state str (optional) CSRF protection state parameter
error str (optional) Error message from provider

Returns: HTML page that uses postMessage() to communicate with opener window

Status Codes:

  • 200 - Returns HTML (success or error)
  • 400 - Missing required code parameter
  • 401 - Provider authentication error
  • 500 - Unexpected error

POST /callback-handler

Purpose: Exchange authorization code for token (frontend-initiated flow)

@router.post("/callback-handler")
async def handle_callback(request: Request, auth_manager: AuthManager = Depends(get_auth_manager))
Request Body Type Description
code str (required) Authorization code from OAuth provider
state str (optional) State parameter for verification

Response:

{
    "token": "eyJhbGc...",
    "user": {
        "id": "12345",
        "name": "John Doe",
        "email": "john@example.com",
        "provider": "github"
    }
}

Status Codes:

  • 200 - Success
  • 400 - Missing authorization code
  • 401 - Provider authentication error
  • 500 - Authentication failed

GET /me

Purpose: Get information about currently authenticated user

@router.get("/me")
async def get_user_info(current_user: User = Depends(get_current_user))

Response:

{
    "id": "12345",
    "name": "John Doe",
    "email": "john@example.com",
    "provider": "github",
    "roles": ["user"]
}

Status Codes:

  • 200 - Success
  • 401 - Not authenticated (via middleware)

GET /type

Purpose: Get configured authentication type and excluded paths

@router.get("/type")
async def get_auth_type(auth_manager: AuthManager = Depends(get_auth_manager))

Response:

{
    "type": "github",
    "exclude_paths": [
        "/",
        "/api/health",
        "/api/version",
        "/api/auth/login-url",
        "/api/auth/callback",
        "/api/auth/type"
    ]
}

Usage Examples

Frontend Login Flow (Popup)

// 1. Get login URL
const response = await fetch('/api/auth/login-url');
const { login_url } = await response.json();

// 2. Open popup
const popup = window.open(login_url, 'oauth', 'width=600,height=700');

// 3. Listen for auth result
window.addEventListener('message', (event) => {
    if (event.data.type === 'auth-success') {
        const { token, user } = event.data;
        localStorage.setItem('auth_token', token);
        console.log('Logged in:', user);
    } else if (event.data.type === 'auth-error') {
        console.error('Auth failed:', event.data.error);
    }
});

Frontend Login Flow (Redirect)

// 1. Get login URL
const response = await fetch('/api/auth/login-url');
const { login_url } = await response.json();

// 2. Redirect to login URL
window.location.href = login_url;

// 3. After redirect to /callback, HTML handles token storage
// User is redirected back to main app with token in localStorage

Frontend Code Exchange

// If frontend handles OAuth redirect directly
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');

const response = await fetch('/api/auth/callback-handler', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code, state })
});

const { token, user } = await response.json();
localStorage.setItem('auth_token', token);

Getting Current User Info

const response = await fetch('/api/auth/me', {
    headers: {
        'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
    }
});

const user = await response.json();
console.log('Current user:', user);

Checking Auth Type

const response = await fetch('/api/auth/type');
const { type, exclude_paths } = await response.json();

if (type === 'none') {
    // No authentication required
} else {
    // Authentication required
}

Including Router in FastAPI App

from fastapi import FastAPI
from autogenstudio.web.auth.authroutes import router as auth_router
from autogenstudio.web.auth.manager import AuthManager

app = FastAPI()

# Initialize auth manager
auth_manager = AuthManager.from_env()
app.state.auth_manager = auth_manager

# Include auth router
app.include_router(auth_router, prefix="/api/auth", tags=["auth"])

Implementation Details

OAuth Callback HTML Response

The callback endpoint returns HTML that communicates with the parent window:

Success HTML:

<script>
window.onload = function() {
    const authResult = {
        type: 'auth-success',
        token: '{token}',
        user: { id: '{user.id}', name: '{user.name}', ... }
    };
    if (window.opener) {
        window.opener.postMessage(authResult, '*');
        window.close();
    } else {
        localStorage.setItem('auth_token', '{token}');
        window.location.href = '/';
    }
};
</script>

Error HTML:

<script>
window.onload = function() {
    if (window.opener) {
        window.opener.postMessage({
            type: 'auth-error',
            error: '{escaped_error}'
        }, '*');
        window.close();
    } else {
        window.location.href = '/?auth_error={escaped_error}';
    }
};
</script>

HTML Escaping

The callback uses html.escape() to prevent XSS attacks:

import html
escaped_error = html.escape(error)

Error Handling

Three types of exceptions are handled:

  1. ProviderAuthException - OAuth provider errors (401)
  2. HTTPException - Request validation errors (400)
  3. General Exception - Unexpected errors (500)

All errors are logged via loguru logger.

Dependency Injection

The module uses FastAPI's dependency injection:

  • get_auth_manager() - Retrieves AuthManager from app.state
  • get_current_user() - Retrieves User from request.state (set by middleware)

Token Creation

After successful authentication:

  1. User object created from provider data
  2. JWT token created via auth_manager.create_token(user)
  3. Token contains: sub (user_id), name, email, provider, roles, exp
  4. Token signed with HS256 algorithm

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment