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 Providers

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

Overview

Description

The Studio Auth Providers module implements authentication provider classes for AutoGen Studio using the Strategy pattern. It defines an abstract AuthProvider interface and provides four concrete implementations: NoAuthProvider (development/default), GithubAuthProvider (GitHub OAuth), MSALAuthProvider (Microsoft/Azure AD - placeholder), and FirebaseAuthProvider (placeholder).

The module encapsulates provider-specific OAuth flows, token exchange logic, and user data retrieval. The GithubAuthProvider is fully implemented with complete OAuth 2.0 flow including authorization code exchange and user information fetching. MSAL and Firebase providers are placeholder implementations intended for future development.

Usage

This module is used to:

  • Implement OAuth flows for different authentication providers
  • Generate login URLs with appropriate parameters and state
  • Exchange authorization codes for access tokens
  • Fetch user information from provider APIs
  • Validate provider tokens for session management

Code Reference

Source Location

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

Class Hierarchy

from abc import ABC, abstractmethod

class AuthProvider(ABC):
    """Base authentication provider interface."""
    @abstractmethod
    async def get_login_url(self) -> str: ...
    @abstractmethod
    async def process_callback(self, code: str, state: str | None = None) -> User: ...
    @abstractmethod
    async def validate_token(self, token: str) -> bool: ...

class NoAuthProvider(AuthProvider):
    """Default provider that always authenticates (for development)."""

class GithubAuthProvider(AuthProvider):
    """GitHub OAuth authentication provider."""

class MSALAuthProvider(AuthProvider):
    """Microsoft Authentication Library (MSAL) provider."""

class FirebaseAuthProvider(AuthProvider):
    """Firebase authentication provider."""

Import Statement

from autogenstudio.web.auth.providers import (
    AuthProvider,
    NoAuthProvider,
    GithubAuthProvider,
    MSALAuthProvider,
    FirebaseAuthProvider
)

Provider Reference

AuthProvider (Abstract Base Class)

Method Returns Description
get_login_url() str Generate OAuth login URL for provider
process_callback(code, state) User Exchange code for token and return User object
validate_token(token) bool Validate provider access token

NoAuthProvider

Development provider that bypasses authentication.

Method Behavior
get_login_url() Returns "/api/auth/callback?automatic=true"
process_callback() Returns default guest user
validate_token() Always returns True

Default User:

User(
    id="guestuser@gmail.com",
    name="Default User",
    email="guestuser@gmail.com",
    provider="none"
)

GithubAuthProvider

Fully implemented GitHub OAuth provider.

Attribute Type Description
client_id str GitHub OAuth app client ID
client_secret str GitHub OAuth app client secret
callback_url str OAuth callback URL
scopes List[str] Requested OAuth scopes

Endpoints Used:

MSALAuthProvider

Placeholder for Microsoft/Azure AD authentication.

Status Description
Implementation Placeholder - returns stub data
get_login_url() Returns https://login.microsoftonline.com/placeholder
process_callback() Returns stub MSAL user
validate_token() Always returns False

FirebaseAuthProvider

Placeholder for Firebase authentication.

Status Description
Implementation Placeholder - returns stub data
get_login_url() Returns JSON config for client-side Firebase init
process_callback() Returns stub Firebase user
validate_token() Always returns False

Usage Examples

Using NoAuthProvider

from autogenstudio.web.auth.providers import NoAuthProvider

provider = NoAuthProvider()

# Get login URL (for consistency)
url = await provider.get_login_url()
print(url)  # "/api/auth/callback?automatic=true"

# Process callback (always succeeds)
user = await provider.process_callback(code=None)
print(user.name)  # "Default User"

# Validate token (always valid)
valid = await provider.validate_token("any-token")
print(valid)  # True

Using GithubAuthProvider

from autogenstudio.web.auth.models import AuthConfig, GithubAuthConfig
from autogenstudio.web.auth.providers import GithubAuthProvider

# Create configuration
config = AuthConfig(
    type="github",
    jwt_secret="secret",
    github=GithubAuthConfig(
        client_id="Iv1.abc123",
        client_secret="secret123",
        callback_url="http://localhost:8000/api/auth/callback",
        scopes=["user:email", "read:user"]
    )
)

# Initialize provider
provider = GithubAuthProvider(config)

# Generate login URL
login_url = await provider.get_login_url()
print(login_url)
# https://github.com/login/oauth/authorize?client_id=Iv1.abc123&redirect_uri=...

# After user authorizes, process callback
code = "authorization_code_from_github"
state = "state_parameter"

user = await provider.process_callback(code, state)
print(f"User: {user.name} ({user.email})")
print(f"GitHub ID: {user.metadata['github_id']}")
print(f"Login: {user.metadata['login']}")

GitHub OAuth Complete Flow

import httpx
from autogenstudio.web.auth.providers import GithubAuthProvider

provider = GithubAuthProvider(config)

# Step 1: Generate login URL with state
login_url = await provider.get_login_url()
# User is redirected to GitHub

# Step 2: GitHub redirects back with code
# GET /callback?code=abc123&state=xyz789

# Step 3: Exchange code for access token
# This happens in process_callback:
# POST https://github.com/login/oauth/access_token
# {
#     "client_id": "...",
#     "client_secret": "...",
#     "code": "abc123",
#     "redirect_uri": "..."
# }

# Step 4: Get user info with access token
# GET https://api.github.com/user
# Authorization: token {access_token}

# Step 5: Get user emails (if scope includes user:email)
# GET https://api.github.com/user/emails
# Authorization: token {access_token}

user = await provider.process_callback("abc123", "xyz789")

Validating GitHub Token

# Validate a GitHub access token
access_token = "gho_abc123xyz789"

valid = await provider.validate_token(access_token)

if valid:
    print("Token is valid")
else:
    print("Token is invalid or expired")

Provider Selection Pattern

from autogenstudio.web.auth.models import AuthConfig
from autogenstudio.web.auth.providers import (
    NoAuthProvider,
    GithubAuthProvider,
    MSALAuthProvider,
    FirebaseAuthProvider
)

def create_provider(config: AuthConfig):
    """Factory function for provider selection."""
    if config.type == "github":
        return GithubAuthProvider(config)
    elif config.type == "msal":
        return MSALAuthProvider(config)
    elif config.type == "firebase":
        return FirebaseAuthProvider(config)
    else:
        return NoAuthProvider()

# Usage
config = AuthConfig(type="github", github=...)
provider = create_provider(config)

Error Handling

from autogenstudio.web.auth.exceptions import (
    ProviderAuthException,
    ConfigurationException
)

try:
    # Missing configuration
    provider = GithubAuthProvider(AuthConfig(type="github"))
except ConfigurationException as e:
    print(f"Config error: {e}")

try:
    # Invalid authorization code
    user = await provider.process_callback("invalid_code")
except ProviderAuthException as e:
    print(f"Auth failed: {e}")
    print(f"Provider: {e.provider}")

Implementation Details

GitHub OAuth State Parameter

The get_login_url() generates a secure random state:

import secrets

state = secrets.token_urlsafe(32)  # 32 bytes = 256 bits

This prevents CSRF attacks by ensuring callbacks originated from legitimate requests.

GitHub Token Exchange

The process_callback() performs token exchange:

async with httpx.AsyncClient() as client:
    token_response = await client.post(
        "https://github.com/login/oauth/access_token",
        data={
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "code": code,
            "redirect_uri": self.callback_url,
        },
        headers={"Accept": "application/json"}
    )

    token_json = token_response.json()
    access_token = token_json.get("access_token")

GitHub User Information

User info is fetched with the access token:

user_response = await client.get(
    "https://api.github.com/user",
    headers={
        "Authorization": f"token {access_token}",
        "Accept": "application/json"
    }
)

user_data = user_response.json()

GitHub Email Retrieval

If "user:email" scope is requested:

if "user:email" in self.scopes:
    email_response = await client.get(
        "https://api.github.com/user/emails",
        headers={"Authorization": f"token {access_token}"}
    )

    emails = email_response.json()
    primary_emails = [e for e in emails if e.get("primary") is True]
    if primary_emails:
        email = primary_emails[0].get("email")

GitHub User Object Construction

return User(
    id=str(user_data.get("id")),
    name=user_data.get("name") or user_data.get("login"),
    email=email,
    avatar_url=user_data.get("avatar_url"),
    provider="github",
    metadata={
        "login": user_data.get("login"),
        "github_id": user_data.get("id"),
        "access_token": access_token,
    }
)

Error Handling

Providers use custom exceptions:

  • ConfigurationException - Missing or invalid config
  • ProviderAuthException - OAuth flow errors

Example:

if not code:
    raise ProviderAuthException("github", "Authorization code is missing")

if token_response.status_code != 200:
    logger.error(f"GitHub token exchange failed: {token_response.text}")
    raise ProviderAuthException("github", "Failed to exchange code for access token")

Logging

Providers use loguru logger for debugging:

from loguru import logger

logger.error(f"GitHub token exchange failed: {token_response.text}")
logger.error(f"No access token in GitHub response: {token_json}")

MSAL Provider Placeholder

The MSAL provider is a placeholder for future implementation:

# Would use msal library:
# from msal import ConfidentialClientApplication

# app = ConfidentialClientApplication(
#     client_id=self.config.client_id,
#     client_credential=self.config.client_secret,
#     authority=f"https://login.microsoftonline.com/{self.config.tenant_id}"
# )

# auth_url = app.get_authorization_request_url(
#     scopes=self.config.scopes,
#     redirect_uri=self.config.callback_url
# )

Firebase Provider Placeholder

Firebase is typically client-side, so get_login_url() returns config:

return json.dumps({
    "apiKey": self.config.api_key,
    "authDomain": self.config.auth_domain,
    "projectId": self.config.project_id
})

The client would use this to initialize Firebase SDK and authenticate.

Related Pages

Page Connections

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