Skip to content

gallettilance/agentic-auth

Repository files navigation

πŸ” Authentication & Authorization System for AI Agents

A comprehensive authentication and authorization system for AI agents with Google OAuth, JWT tokens, scope-based permissions, and real-time approval workflows. Built for secure MCP (Model Context Protocol) tool access with automatic permission escalation.

🎯 What This System Does

This system provides secure, granular access control for AI agents interacting with system resources. Users authenticate once via Google OAuth, then the system automatically manages permissions as AI agents request access to different tools and resources.

Key Capabilities

  • πŸ” Google OAuth Authentication - Secure login with Google accounts
  • 🎫 JWT Token Management - Automatic token generation and refresh
  • πŸ”§ MCP Tool Integration - Secure access to file system, commands, and APIs
  • πŸ“‹ Dynamic Approval Workflows - Auto-approve safe operations, require admin approval for risky ones
  • πŸ€– AI Agent Integration - Llama Stack agents with secure tool access
  • πŸ‘‘ Admin Dashboard - Real-time approval management and user oversight
  • πŸ”„ Auto-Retry Logic - Seamless user experience when permissions are granted

πŸ—οΈ System Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Chat UI       β”‚    β”‚   Auth Server   β”‚    β”‚   MCP Server    β”‚
β”‚   (Flask)       │◄──►│   (FastAPI)     β”‚    β”‚   (FastMCP)     β”‚
β”‚   Port 5001     β”‚    β”‚   Port 8002     β”‚    β”‚   Port 8001     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                       β”‚                       β”‚
         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                 β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  Llama Stack    β”‚    β”‚ Admin Dashboard β”‚
                    β”‚  (AI Agents)    β”‚    β”‚   (Flask)       β”‚
                    β”‚  Port 8321      β”‚    β”‚   Port 8003     β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Prerequisites

# Python 3.12+ required
python --version

# Install dependencies
pip install -r requirements.txt

Browser Recommendation

🌐 Recommended Browser: Google Chrome

  • OAuth flows are optimized for Chrome
  • Token debugging features work best in Chrome
  • Cookie management is most reliable in Chrome

Environment Setup

# Copy environment template
cp env.example .env

# Edit .env file with your settings:
# - ADMIN_EMAIL (required)
# - OPENAI_API_KEY (required for AI agents)
# - GOOGLE_CLIENT_ID/SECRET (required for Google OAuth)

Start the System

# One command to start everything
./start_demo.sh

# Access the applications:
# - Chat UI: http://localhost:5001
# - Admin Dashboard: http://localhost:8003/dashboard
# - Auth Server: http://localhost:8002

Stop the System

# Stop all services (preserves data)
./stop_demo.sh

# Complete cleanup (removes all data)
./cleanup_demo.sh

⚠️ Important: stop_demo.sh will force close Chrome to clear authentication cookies. Save any important Chrome work before running this command.

πŸ” Google OAuth Setup

Before running the demo, you need to set up Google OAuth credentials. Follow these steps:

1. Create Google Cloud Project

  1. Go to Google Cloud Console: https://console.cloud.google.com/
  2. Create a new project or select an existing one
  3. Enable the Google+ API:
    • Go to "APIs & Services" > "Library"
    • Search for "Google+ API"
    • Click "Enable"

2. Configure OAuth Consent Screen

  1. Go to "APIs & Services" > "OAuth consent screen"
  2. Choose "External" user type (unless you have a Google Workspace)
  3. Fill in required fields:
    • App name: Authentication Demo
    • User support email: Your email
    • Developer contact email: Your email
  4. Add scopes (click "Add or Remove Scopes"):
    • openid
    • email
    • profile
  5. Add test users (for External apps):
    • Add your email address and any other emails you want to test with
  6. Save and continue through all steps

3. Create OAuth Credentials

  1. Go to "APIs & Services" > "Credentials"
  2. Click "Create Credentials" > "OAuth 2.0 Client ID"
  3. Choose "Web application"
  4. Configure the client:
    • Name: Authentication Demo Client
    • Authorized JavaScript origins:
      http://localhost:5001
      http://localhost:8002
      http://localhost:8003
      
    • Authorized redirect URIs:
      http://localhost:8002/auth/callback
      http://localhost:5001/callback
      http://localhost:8003/callback
      
  5. Click "Create"
  6. Copy the Client ID and Client Secret - you'll need these for your .env file

4. Update Environment Variables

Add your Google OAuth credentials to your .env file:

# Required Google OAuth credentials
GOOGLE_CLIENT_ID="your-client-id-here.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="your-client-secret-here"

# Other required variables
ADMIN_EMAIL="your-admin@example.com"
OPENAI_API_KEY="your-openai-api-key"

5. Test Your Setup

  1. Start the demo: ./start_demo.sh
  2. Visit: http://localhost:5001
  3. Click login - you should be redirected to Google
  4. Sign in with a test user email you added
  5. Grant permissions to the app
  6. You should be redirected back to the chat interface

🚨 Common OAuth Issues

"Error 400: redirect_uri_mismatch"

# Check your redirect URIs in Google Cloud Console
# Make sure you have: http://localhost:8002/auth/callback

"Error 403: access_denied"

# Add your email as a test user in OAuth consent screen
# Or publish your app (not recommended for development)

"Error 401: invalid_client"

# Check your GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in .env
# Make sure there are no extra spaces or quotes

πŸ”„ System Overview & Authentication Flow

System Components Overview

System Overview

OAuth and MCP Token Discovery Flow

The following diagram shows the streamlined OAuth authentication and MCP token discovery process:

OAuth MCP Discovery Flow

How It Works

  1. πŸ” Initial Authentication

    • User accesses Chat UI β†’ redirected to Google OAuth
    • After OAuth success β†’ user gets Llama Stack session token
    • Session token enables basic chat functionality
  2. πŸ”§ Tool Discovery & Authorization

    • AI agent attempts to use MCP tool β†’ gets 403 (insufficient scope)
    • System automatically requests required scope from auth server
    • Auth server evaluates policy: auto-approve safe tools, require admin approval for risky ones
  3. 🎫 Token Exchange & Upgrade

    • For auto-approved scopes: immediate token upgrade
    • For admin-required scopes: approval workflow with admin dashboard
    • User gets both Llama Stack and MCP tokens with appropriate scopes
  4. βœ… Seamless Execution

    • User retries request with new permissions
    • AI agent successfully executes tool with valid scope
    • Future requests use cached tokens until expiration

πŸ“‹ Demo Walkthrough

1. First-Time User Experience

  1. Access http://localhost:5001
  2. Login with Google OAuth
  3. Start with no permissions - secure by default
  4. Try a command: "List files in /tmp"
  5. See auto-approval for safe operations
  6. View updated permissions in token dashboard

2. Admin Approval Workflow

  1. Try risky command: "Execute command: ls -la"
  2. See approval request created automatically
  3. Admin reviews in dashboard at http://localhost:8003/dashboard
  4. Approve/deny with justification
  5. User gets notification and can retry

3. Token Management

  1. View token dashboard in chat UI
  2. See current scopes and permissions
  3. Debug tokens with JWT.io integration
  4. Monitor real-time updates every 5 seconds

πŸ”§ Configuration

Environment Variables

# Required
ADMIN_EMAIL="your-admin@example.com"
OPENAI_API_KEY="your-openai-api-key"
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

# Advanced
JWT_MODE="asymmetric"  # or "symmetric"
AUTH_SERVER_URL="http://localhost:8002"

Permission Policies

The system uses database-driven policies for different scopes:

Scope Description Policy Risk Level
list_files List directory contents Auto-approve Low
read_file Read file contents Auto-approve Low
health_check System health check Auto-approve Low
execute_command Run system commands Admin approval Critical
write_file Write to files Admin approval High
delete_file Delete files Admin approval High

πŸ›‘οΈ Security Features

Zero-Trust Architecture

  • Users start with no permissions - even returning users
  • Dynamic permission escalation via token exchange
  • Every tool request is validated against current token scopes
  • Admin oversight for high-risk operations

JWT Token Security

  • Asymmetric RS256 signing with auto-generated keys
  • JWKS endpoint for public key distribution
  • Token expiration and refresh mechanisms
  • Secure cookie handling across all services

Audit & Monitoring

  • Complete audit trail of all permission requests
  • Real-time approval workflows with admin notifications
  • Comprehensive logging across all services
  • JWT.io integration for token debugging

πŸ“ Project Structure

Authentication/
β”œβ”€β”€ auth-server/                    # Authentication server
β”‚   β”œβ”€β”€ main.py                    # FastAPI application
β”‚   β”œβ”€β”€ database.py                # SQLite database operations
β”‚   β”œβ”€β”€ api/                       # API routes
β”‚   β”œβ”€β”€ auth/                      # Authentication logic
β”‚   β”œβ”€β”€ utils/                     # Utilities (JWT, MCP, etc.)
β”‚   └── config/                    # Configuration
β”œβ”€β”€ frontends/
β”‚   β”œβ”€β”€ chat-ui/                   # Chat interface
β”‚   β”‚   β”œβ”€β”€ app.py                 # Flask application
β”‚   β”‚   β”œβ”€β”€ api/                   # API blueprints
β”‚   β”‚   β”œβ”€β”€ templates/             # HTML templates
β”‚   β”‚   └── utils/                 # Utility functions
β”‚   └── admin-dashboard/           # Admin interface
β”‚       β”œβ”€β”€ app.py                 # Flask application
β”‚       └── templates/             # HTML templates
β”œβ”€β”€ mcp/                           # MCP server
β”‚   β”œβ”€β”€ mcp_server.py              # FastMCP server
β”‚   └── README.md                  # MCP documentation
β”œβ”€β”€ services/                      # Llama Stack configuration
β”‚   β”œβ”€β”€ stack/run.yml              # Llama Stack config
β”‚   └── auth-agent/                # Custom auth agent
β”œβ”€β”€ diagrams/                      # Architecture diagrams
β”‚   β”œβ”€β”€ oauth-mcp-discovery-flow.mmd  # OAuth & MCP token flow
β”‚   β”œβ”€β”€ system-overview.mmd        # System components overview
β”‚   └── *.svg                      # Rendered diagrams
β”œβ”€β”€ start_demo.sh                  # One-command startup
β”œβ”€β”€ stop_demo.sh                   # Stop all services
└── cleanup_demo.sh                # Complete cleanup

πŸ” API Endpoints

Chat UI (Port 5001)

GET  /                             # Chat interface
GET  /callback                     # OAuth callback
POST /api/chat                     # Send message
GET  /api/chat-history             # Get chat history
GET  /api/token-info               # Token dashboard data

Auth Server (Port 8002)

GET  /auth/authorize               # OAuth authorization
POST /auth/token                   # Token exchange
GET  /api/user-status              # Check authentication
POST /api/upgrade-scope            # Request scope upgrade
GET  /.well-known/jwks.json        # Public keys

Admin Dashboard (Port 8003)

GET  /dashboard                    # Admin interface
GET  /api/pending-approvals        # Pending requests
POST /api/approve/{id}             # Approve request
POST /api/deny/{id}                # Deny request

πŸ› οΈ Development

Running Individual Services

# Auth Server
cd auth-server
python main.py

# Chat UI
cd frontends/chat-ui
python app.py

# Admin Dashboard
cd frontends/admin-dashboard
python app.py

# MCP Server
cd mcp
python mcp_server.py

Database Management

# View database contents
sqlite3 auth-server/auth.db

# Check users and roles
SELECT * FROM users;
SELECT * FROM user_roles;

# View approval policies
SELECT * FROM scope_policies;

🚨 Troubleshooting

Common Issues

Services won't start:

# Check for port conflicts
lsof -i :5001 -i :5002 -i :8001 -i :8002 -i :8321

# Kill existing processes
./stop_demo.sh

Authorization not working:

# Check auth server logs
tail -f logs/auth-server.log

# Verify token in JWT.io
# (Use links in chat UI token dashboard)

Google OAuth setup required:

# Check Google OAuth credentials in .env
cat .env | grep GOOGLE_

# Verify auth server is running
curl http://localhost:8002/health

🀝 Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Test with demo: ./start_demo.sh
  4. Commit changes: git commit -m 'Add amazing feature'
  5. Push to branch: git push origin feature/amazing-feature
  6. Open Pull Request

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • RFC 8693 Token Exchange specification
  • FastAPI and Flask web frameworks
  • FastMCP for Model Context Protocol
  • Llama Stack for AI agent integration
  • JWT.io for token debugging tools

🌟 This system provides enterprise-grade authentication with zero-trust security, automatic user onboarding, and real-time permission management for AI agent interactions.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •