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 Manager

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

Overview

Description

The Studio Auth Manager module implements the AuthManager class, which serves as the central authentication management system for AutoGen Studio. It handles token creation, validation, request authentication, and provider selection based on configuration. The manager supports multiple authentication providers (GitHub, MSAL, Firebase, None) and uses JWT tokens for session management.

The AuthManager follows the Factory pattern for provider creation and provides class methods for configuration loading from YAML files or environment variables. It integrates seamlessly with FastAPI middleware for request-level authentication.

Usage

This module is used to:

  • Create and validate JWT tokens for authenticated users
  • Select and initialize auth providers based on configuration
  • Authenticate incoming requests by validating bearer tokens
  • Load configuration from YAML files or environment variables
  • Manage token expiry and validation logic

Code Reference

Source Location

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

Class Signature

class AuthManager:
    """
    Manages authentication for the application.
    Handles token creation, validation, and provider selection.
    """

    def __init__(self, config: AuthConfig): ...
    def _create_provider(self) -> AuthProvider: ...
    def create_token(self, user: User) -> str: ...
    async def authenticate_request(self, request: Request) -> User: ...
    def is_valid_token(self, token: str) -> bool: ...

    @classmethod
    def from_yaml(cls, yaml_path: str) -> Self: ...

    @classmethod
    def from_env(cls) -> Self: ...

Import Statement

from autogenstudio.web.auth.manager import AuthManager

I/O Contract

Constructor

Parameter Type Description
config AuthConfig Authentication configuration including type, secrets, and provider configs

Instance Attributes

Attribute Type Description
config AuthConfig Authentication configuration
provider AuthProvider Selected authentication provider (GithubAuthProvider, MSALAuthProvider, FirebaseAuthProvider, NoAuthProvider)

create_token()

Parameter Type Description
user User Authenticated user object

Returns: JWT token string

Payload Structure:

{
    "sub": "user_id",
    "name": "User Name",
    "email": "user@example.com",
    "provider": "github",
    "roles": ["user"],
    "exp": 1738432800
}

authenticate_request()

Parameter Type Description
request Request FastAPI Request object

Returns: User object

Raises:

  • MissingTokenException - No Authorization header or invalid format
  • InvalidTokenException - Token expired or invalid signature

is_valid_token()

Parameter Type Description
token str JWT token to validate

Returns: Boolean indicating validity

from_yaml()

Parameter Type Description
yaml_path str Path to YAML configuration file

Returns: AuthManager instance

Raises: ConfigurationException on load failure

from_env()

Returns: AuthManager instance configured from environment variables

Environment Variables:

Variable Description
AUTOGENSTUDIO_AUTH_TYPE Auth type: "none", "github", "msal", "firebase"
AUTOGENSTUDIO_JWT_SECRET Secret key for JWT signing
AUTOGENSTUDIO_TOKEN_EXPIRY Token expiry in minutes (default: 60)
AUTOGENSTUDIO_GITHUB_CLIENT_ID GitHub OAuth client ID
AUTOGENSTUDIO_GITHUB_CLIENT_SECRET GitHub OAuth client secret
AUTOGENSTUDIO_GITHUB_CALLBACK_URL GitHub OAuth callback URL
AUTOGENSTUDIO_GITHUB_SCOPES Comma-separated GitHub scopes

Usage Examples

Initialization from Environment

import os
from autogenstudio.web.auth.manager import AuthManager

# Set environment variables
os.environ['AUTOGENSTUDIO_AUTH_TYPE'] = 'github'
os.environ['AUTOGENSTUDIO_JWT_SECRET'] = 'your-secret-key-here'
os.environ['AUTOGENSTUDIO_GITHUB_CLIENT_ID'] = 'your-client-id'
os.environ['AUTOGENSTUDIO_GITHUB_CLIENT_SECRET'] = 'your-client-secret'
os.environ['AUTOGENSTUDIO_GITHUB_CALLBACK_URL'] = 'http://localhost:8000/api/auth/callback'

# Create manager
auth_manager = AuthManager.from_env()
print(f"Auth type: {auth_manager.config.type}")

Initialization from YAML

# config.yaml:
# type: github
# jwt_secret: my-secret-key
# token_expiry_minutes: 120
# github:
#   client_id: abc123
#   client_secret: secret123
#   callback_url: http://localhost:8000/api/auth/callback
#   scopes: [user:email, read:user]

auth_manager = AuthManager.from_yaml('config.yaml')

Creating Tokens

from autogenstudio.web.auth.models import User

# Create user object (typically from OAuth provider)
user = User(
    id="12345",
    name="John Doe",
    email="john@example.com",
    provider="github",
    roles=["user", "admin"]
)

# Create JWT token
token = auth_manager.create_token(user)
print(f"Token: {token}")
# Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Authenticating Requests

from fastapi import Request, HTTPException
from autogenstudio.web.auth.exceptions import MissingTokenException, InvalidTokenException

async def protected_route(request: Request):
    try:
        user = await auth_manager.authenticate_request(request)
        return {"user": user.name, "email": user.email}
    except MissingTokenException:
        raise HTTPException(status_code=401, detail="No token provided")
    except InvalidTokenException:
        raise HTTPException(status_code=401, detail="Invalid token")

Validating Tokens

# Validate a token without extracting payload
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

if auth_manager.is_valid_token(token):
    print("Token is valid")
else:
    print("Token is invalid or expired")

Integration with FastAPI

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

app = FastAPI()

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

# Add authentication middleware
app.add_middleware(AuthMiddleware, auth_manager=auth_manager)

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

@app.get("/api/protected")
async def protected_route(request: Request):
    # User automatically populated by middleware
    user = request.state.user
    return {"message": f"Hello {user.name}"}

No-Auth Mode

# For development without authentication
os.environ['AUTOGENSTUDIO_AUTH_TYPE'] = 'none'

auth_manager = AuthManager.from_env()

# All requests return default user
user = await auth_manager.authenticate_request(request)
print(user.id)  # "guestuser@gmail.com"
print(user.name)  # "Default User"

Custom Provider Selection

# The manager automatically selects provider based on config
from autogenstudio.web.auth.models import AuthConfig, GithubAuthConfig

config = AuthConfig(
    type="github",
    jwt_secret="my-secret",
    github=GithubAuthConfig(
        client_id="abc123",
        client_secret="secret123",
        callback_url="http://localhost:8000/callback",
        scopes=["user:email"]
    )
)

auth_manager = AuthManager(config)
print(type(auth_manager.provider))  # <class 'GithubAuthProvider'>

Implementation Details

Provider Factory

The _create_provider() method implements the Factory pattern:

def _create_provider(self) -> AuthProvider:
    try:
        if self.config.type == "github":
            return GithubAuthProvider(self.config)
        elif self.config.type == "msal":
            return MSALAuthProvider(self.config)
        elif self.config.type == "firebase":
            return FirebaseAuthProvider(self.config)
        else:
            return NoAuthProvider()
    except Exception as e:
        logger.error(f"Failed to create auth provider: {str(e)}")
        # Fall back to no auth if provider creation fails
        return NoAuthProvider()

JWT Token Creation

Tokens are created using PyJWT library:

  • Algorithm: HS256
  • Expiry: Configurable (default 60 minutes)
  • Payload includes user metadata
  • Fallback to insecure dummy token if no JWT secret

Request Authentication Flow

  1. Check if path is in exclude_paths → return default user
  2. Check if auth type is "none" → return default user
  3. Extract Authorization header
  4. Validate "Bearer " prefix
  5. Decode JWT with HS256 algorithm
  6. Verify expiry and signature
  7. Return User object from payload
  8. On error: raise MissingTokenException or InvalidTokenException

Excluded Paths

The following paths bypass authentication by default:

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

Additional paths can be added in AuthConfig.

Error Handling

Token validation errors are categorized:

  • jwt.ExpiredSignatureError → InvalidTokenException
  • jwt.InvalidTokenError → InvalidTokenException
  • Errors logged with token prefix (first 10 chars)

Development Mode

When JWT secret is not configured:

  • create_token() returns "dummy_token_" + user_id
  • authenticate_request() accepts all tokens
  • is_valid_token() always returns True
  • Warning logged for insecure operation

Related Pages

Page Connections

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