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 Models

From Leeroopedia
Metadata
Sources python/packages/autogen-studio/autogenstudio/web/auth/models.py
Domains Authentication, Data_Models, Configuration, Pydantic
Last Updated 2026-02-11 17:00 GMT

Overview

Description

The Studio Auth Models module defines Pydantic data models for authentication configuration and user representation in AutoGen Studio. It provides type-safe configuration models for multiple authentication providers (GitHub, MSAL, Firebase) and a unified User model for representing authenticated users across all providers.

The module uses Pydantic's field validators to ensure configuration consistency and prevent misconfiguration. Each provider has its own configuration model, and the main AuthConfig model uses discriminated types to enforce provider-specific requirements.

Usage

This module is used to:

  • Define authentication configuration with type safety
  • Represent authenticated users across different providers
  • Validate configuration at initialization time
  • Serialize/deserialize auth data for storage and transmission

Code Reference

Source Location

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

Model Definitions

from pydantic import BaseModel, Field, field_validator
from typing import Any, Dict, List, Literal, Optional, Union

class GithubAuthConfig(BaseModel):
    client_id: str
    client_secret: str
    callback_url: str
    scopes: List[str] = ["user:email"]

class MSALAuthConfig(BaseModel):
    tenant_id: str
    client_id: str
    client_secret: str
    callback_url: str
    scopes: List[str] = ["User.Read"]

class FirebaseAuthConfig(BaseModel):
    api_key: str
    auth_domain: str
    project_id: str

class AuthConfig(BaseModel):
    type: Literal["none", "github", "msal", "firebase"] = "none"
    github: Optional[GithubAuthConfig] = None
    msal: Optional[MSALAuthConfig] = None
    firebase: Optional[FirebaseAuthConfig] = None
    jwt_secret: Optional[str] = None
    token_expiry_minutes: int = 60
    exclude_paths: List[str] = [...]

class User(BaseModel):
    id: str
    name: str
    email: Optional[str] = None
    avatar_url: Optional[str] = None
    provider: Optional[str] = None
    roles: List[str] = ["user"]
    metadata: Optional[Dict[str, Any]] = None

Import Statement

from autogenstudio.web.auth.models import (
    AuthConfig,
    GithubAuthConfig,
    MSALAuthConfig,
    FirebaseAuthConfig,
    User
)

Model Reference

GithubAuthConfig

Configuration for GitHub OAuth authentication.

Field Type Required Default Description
client_id str Yes - GitHub OAuth app client ID
client_secret str Yes - GitHub OAuth app client secret
callback_url str Yes - OAuth callback URL (must match GitHub app config)
scopes List[str] No ["user:email"] OAuth scopes to request

MSALAuthConfig

Configuration for Microsoft Authentication Library (MSAL/Azure AD).

Field Type Required Default Description
tenant_id str Yes - Azure AD tenant ID
client_id str Yes - Azure AD application (client) ID
client_secret str Yes - Azure AD client secret
callback_url str Yes - OAuth callback URL
scopes List[str] No ["User.Read"] Microsoft Graph API scopes

FirebaseAuthConfig

Configuration for Firebase authentication.

Field Type Required Default Description
api_key str Yes - Firebase API key
auth_domain str Yes - Firebase auth domain (e.g., project-id.firebaseapp.com)
project_id str Yes - Firebase project ID

AuthConfig

Main authentication configuration model with provider-specific validation.

Field Type Required Default Description
type Literal["none", "github", "msal", "firebase"] No "none" Authentication provider type
github Optional[GithubAuthConfig] Conditional None GitHub config (required if type="github")
msal Optional[MSALAuthConfig] Conditional None MSAL config (required if type="msal")
firebase Optional[FirebaseAuthConfig] Conditional None Firebase config (required if type="firebase")
jwt_secret Optional[str] Conditional None JWT signing secret (required if type != "none")
token_expiry_minutes int No 60 JWT token expiry duration in minutes
exclude_paths List[str] No See below Paths excluded from authentication

Default Excluded Paths:

  • /
  • /api/health
  • /api/version
  • /api/auth/login-url
  • /api/auth/callback-handler
  • /api/auth/callback
  • /api/auth/type

User

Represents an authenticated user across all provider types.

Field Type Required Default Description
id str Yes - Unique user identifier (from provider or custom)
name str Yes - User's display name
email Optional[str] No None User's email address
avatar_url Optional[str] No None URL to user's avatar image
provider Optional[str] No None Authentication provider ("github", "msal", "firebase", "none")
roles List[str] No ["user"] User roles for authorization
metadata Optional[Dict[str, Any]] No None Provider-specific metadata

Usage Examples

Creating GitHub Configuration

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

config = AuthConfig(
    type="github",
    jwt_secret="my-secure-secret-key",
    token_expiry_minutes=120,
    github=GithubAuthConfig(
        client_id="Iv1.abc123def456",
        client_secret="secretkey123",
        callback_url="http://localhost:8000/api/auth/callback",
        scopes=["user:email", "read:user"]
    )
)

print(config.type)  # "github"
print(config.github.client_id)  # "Iv1.abc123def456"

Creating MSAL Configuration

from autogenstudio.web.auth.models import AuthConfig, MSALAuthConfig

config = AuthConfig(
    type="msal",
    jwt_secret="my-secret",
    msal=MSALAuthConfig(
        tenant_id="12345678-1234-1234-1234-123456789abc",
        client_id="abcdefgh-1234-5678-90ab-cdef12345678",
        client_secret="client-secret-here",
        callback_url="http://localhost:8000/api/auth/callback",
        scopes=["User.Read", "Mail.Read"]
    )
)

Creating Firebase Configuration

from autogenstudio.web.auth.models import AuthConfig, FirebaseAuthConfig

config = AuthConfig(
    type="firebase",
    jwt_secret="my-secret",
    firebase=FirebaseAuthConfig(
        api_key="AIzaSyAbCdEfGhIjKlMnOpQrStUvWxYz",
        auth_domain="my-project.firebaseapp.com",
        project_id="my-project"
    )
)

No-Auth Configuration

from autogenstudio.web.auth.models import AuthConfig

# Minimal config for development
config = AuthConfig(type="none")

print(config.type)  # "none"
print(config.jwt_secret)  # None

Creating User Objects

from autogenstudio.web.auth.models import User

# GitHub user
github_user = User(
    id="12345678",
    name="John Doe",
    email="john@example.com",
    avatar_url="https://avatars.githubusercontent.com/u/12345678",
    provider="github",
    roles=["user"],
    metadata={
        "login": "johndoe",
        "github_id": 12345678,
        "access_token": "gho_..."
    }
)

# Default/anonymous user
default_user = User(
    id="guestuser@gmail.com",
    name="Default User",
    provider="none"
)

# Admin user
admin_user = User(
    id="admin123",
    name="Admin User",
    email="admin@example.com",
    provider="github",
    roles=["user", "admin"]
)

Loading from Dictionary

config_dict = {
    "type": "github",
    "jwt_secret": "secret",
    "token_expiry_minutes": 90,
    "github": {
        "client_id": "abc123",
        "client_secret": "secret123",
        "callback_url": "http://localhost:8000/callback",
        "scopes": ["user:email"]
    }
}

config = AuthConfig(**config_dict)

Serializing to JSON

config = AuthConfig(
    type="github",
    jwt_secret="secret",
    github=GithubAuthConfig(
        client_id="abc123",
        client_secret="secret123",
        callback_url="http://localhost:8000/callback"
    )
)

# Convert to dict
config_dict = config.model_dump()

# Convert to JSON
import json
config_json = json.dumps(config.model_dump(), indent=2)

Custom Exclude Paths

config = AuthConfig(
    type="github",
    jwt_secret="secret",
    github=GithubAuthConfig(...),
    exclude_paths=[
        "/",
        "/api/health",
        "/api/public",
        "/api/docs",
        "/metrics"
    ]
)

Validation Logic

GitHub Validation

@field_validator("github")
@classmethod
def validate_github_config(cls, v, info):
    """Validate GitHub config is present when github type is selected."""
    values = info.data
    if values.get("type") == "github" and v is None:
        raise ValueError("GitHub configuration required when type is 'github'")
    return v

Example:

# This will raise ValueError
config = AuthConfig(type="github")  # Missing github config

MSAL Validation

@field_validator("msal")
@classmethod
def validate_msal_config(cls, v, info):
    """Validate MSAL config is present when msal type is selected."""
    values = info.data
    if values.get("type") == "msal" and v is None:
        raise ValueError("MSAL configuration required when type is 'msal'")
    return v

Firebase Validation

@field_validator("firebase")
@classmethod
def validate_firebase_config(cls, v, info):
    """Validate Firebase config is present when firebase type is selected."""
    values = info.data
    if values.get("type") == "firebase" and v is None:
        raise ValueError("Firebase configuration required when type is 'firebase'")
    return v

JWT Secret Validation

@field_validator("jwt_secret")
@classmethod
def validate_jwt_secret(cls, v, info):
    """Validate JWT secret is present for auth types other than 'none'."""
    values = info.data
    if values.get("type") != "none" and not v:
        raise ValueError("JWT secret is required for authentication")
    return v

Example:

# This will raise ValueError
config = AuthConfig(
    type="github",
    github=GithubAuthConfig(...)
)  # Missing jwt_secret

Implementation Details

Pydantic V2 Features

The module uses Pydantic V2 features:

  • field_validator - Replaces V1's @validator decorator
  • info.data - Access to other field values during validation
  • model_dump() - Replaces V1's dict() method
  • BaseModel inheritance for all models

Type Safety

Literal types ensure auth type is one of valid options:

type: Literal["none", "github", "msal", "firebase"] = "none"

Invalid values are rejected at instantiation:

# This will raise ValidationError
config = AuthConfig(type="invalid")

Optional vs Required Fields

Provider configs are optional but validated:

  • github is Optional[GithubAuthConfig]
  • But validator ensures it's present when type="github"

This allows flexible configuration while preventing misconfiguration.

Default Values

Several fields have sensible defaults:

  • type="none" - No auth by default
  • token_expiry_minutes=60 - 1 hour expiry
  • scopes have provider-specific defaults
  • roles=["user"] - Basic user role
  • exclude_paths has comprehensive default list

Metadata Field

The User model includes a flexible metadata field:

metadata: Optional[Dict[str, Any]] = None

This allows providers to store additional data:

  • GitHub: login, github_id, access_token
  • MSAL: tenant, upn, groups
  • Firebase: uid, custom_claims

Related Pages

Page Connections

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