This is a submission for the Auth0 for AI Agents Challenge
What I Built
SecureDoc AI Assistant is an intelligent document management system that demonstrates how Auth0 for AI Agents can secure AI-powered applications with fine-grained access control.
The Problem
Organizations struggle with a critical challenge: How do you let AI agents help employees find information while ensuring they only access documents they're authorized to see?
Traditional solutions either:
- Give AI agents too much access (security risk)
- Restrict AI too heavily (poor user experience)
- Lack proper audit trails (compliance issues)
The Solution
SecureDoc AI Assistant solves this by implementing permission-aware AI agents that:
- โ Authenticate users with Auth0
- โ Filter documents based on role and department
- โ Only retrieve authorized content for AI context
- โ Track every action in a comprehensive audit trail
Demo
Live Demo
GitHub
๐ธ Screenshots
Landing Page - Clean, Professional Design
AI Chat with Source Citations
Ask questions and get answers from authorized documents only
-
Manager
fromEngineering
department accessingEngineering-related information
-
Employee
fromMarketing
department accessingEngineering-related information
-
Guest
accessingEngineering-related information
Role-Based Document Access
Different users see different documents based on their role
- Role: Employee
- Role: Guest
Department-Filtered Audit Trail
Track all AI agent actions with department-level filtering
- Role: Admin
- Role: Manager
- Role: Employee
Auth0 Users Configuration
- User configuration
- Roles configuration
๐ฎ Try It Yourself
Test Users (Password: Test1234!
):
Role | Department | Documents | Audit | Chat | |
---|---|---|---|---|---|
admin@company.com |
Admin | All | 7 (all) | All logs | Full access |
john.smith@company.com |
Manager | Engineering | 3 | Engineering logs | Engineering docs |
sarah.johnson@company.com |
Manager | Marketing | 2 | Marketing logs | Marketing docs |
emily.wong@company.com |
Employee | Engineering | 3 | โ | Engineering docs |
lisa.anderson@company.com |
Employee | Marketing | 2 | โ | Marketing docs |
guest@company.com |
Guest | - | 0 | โ | No context |
Try Different Scenarios:
- Login as Admin โ See all 7 documents, all audit logs
- Login as Engineering Manager โ See only engineering docs, only engineering audit logs
- Login as Marketing Manager โ See only marketing docs, only marketing audit logs
- Login as Employee โ See limited docs, no audit access
- Login as Guest โ See no documents, no audit access
๐ Complete Access Rules Matrix
Document Access by Role & Department:
Document | Department | Admin | Eng Manager | Mkt Manager | Eng Employee | Mkt Employee | Guest |
---|---|---|---|---|---|---|---|
Q4 Engineering Roadmap | Engineering | โ | โ | โ | โ | โ | โ |
API Documentation | Engineering | โ | โ | โ | โ | โ | โ |
Security Incident Plan | Engineering | โ | โ | โ | โ | โ | โ |
Marketing Campaign Strategy | Marketing | โ | โ | โ | โ | โ | โ |
Employee Handbook | HR | โ | โ | โ | โ | โ | โ |
Sales Playbook | Sales | โ | โ | โ | โ | โ | โ |
Financial Report Q3 | Finance | โ | โ | โ | โ | โ | โ |
Feature Access by Role:
Feature | Admin | Manager | Employee | Guest |
---|---|---|---|---|
View Documents | All (7) | Department (2-4) | Limited (1-3) | None (0) |
AI Chat | Full context | Department context | Limited context | No context |
Search Documents | All docs | Department docs | Limited docs | None |
View Audit Logs | All logs | Department logs | โ | โ |
Document Details | โ | โ | โ | โ |
Audit Log Visibility:
Viewer Role | Can See Logs From |
---|---|
Admin | All users, all departments |
Engineering Manager | Only Engineering department users |
Marketing Manager | Only Marketing department users |
Employee | No access (403 Forbidden) |
Guest | No access (403 Forbidden) |
Example Scenarios:
-
Cross-Department Privacy:
- Engineering Manager asks about "marketing budget"
- AI Response: "No relevant documents found" (no access to Marketing docs)
- Audit: Engineering Manager's query logged in Engineering logs only
-
Role-Based Restrictions:
- Employee asks about "financial report"
- AI Response: "No access" (Finance docs are Manager+ only)
- Audit: Employee's attempt logged but document not accessed
-
Department Isolation:
- Marketing Manager views audit logs
- Sees: Marketing team activities only
- Does NOT see: Engineering, Finance, or other department activities
-
Guest Lockdown:
- Guest user tries to access documents
- Result: "No documents found"
- Audit: Guest cannot view audit logs (403)
How I Used Auth0 for AI Agents
1. ๐ User Authentication
Challenge Requirement: Authenticate the user - Secure the human who is prompting the agent
Implementation:
// Auth0 SDK integration with Next.js
import { getSession } from '@auth0/nextjs-auth0';
export async function getCurrentUser(): Promise<User | null> {
const session = await getSession();
if (!session?.user) return null;
// Map Auth0 user to our role system
return mapAuth0User(session.user);
}
Features:
- โ Secure session management with encrypted cookies
- โ Protected routes via middleware
- โ
Role-Based Access Control (RBAC) with 4 levels:
- Admin: Full access to all documents
- Manager: Department-level access + audit logs
- Employee: Limited document access
- Guest: No document access
Why This Matters:
Every AI query is tied to an authenticated user with specific permissions. The AI can only access what the user is authorized to see.
2. ๐ Token Vault
Challenge Requirement: Control the tools - Manage which APIs your agent can call
Implementation:
// Secure API key management
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
export async function generateChatResponse(messages, context) {
const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
headers: {
'Authorization': `Bearer ${OPENROUTER_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'meta-llama/llama-3.2-3b-instruct:free',
messages: apiMessages
})
});
return response.json();
}
Features:
- โ Environment-based API key storage
- โ No hardcoded credentials
- โ Secure token management for AI service (OpenRouter)
- โ
Proper secret handling with
.env.local
Why This Matters:
The AI agent's API credentials are managed securely, preventing unauthorized access to the AI service while enabling legitimate use.
3. ๐ฏ Fine-Grained RAG Authorization
Challenge Requirement: Limit knowledge - Apply fine-grained authorization to RAG pipelines
Implementation:
// Permission-aware RAG pipeline
export class RAGService {
async initialize(user: User): Promise<void> {
// Get ONLY documents the user can access
const documents = this.documentService.getAll(user);
// Generate embeddings only for authorized documents
for (const doc of documents) {
const chunks = this.chunkDocument(doc);
for (const chunk of chunks) {
const embedding = await this.generateEmbedding(chunk.content);
this.chunks.set(chunk.id, { ...chunk, embedding });
}
}
}
async query(userQuery: string, user: User): Promise<DocumentReference[]> {
// Search only through user's accessible documents
const accessibleChunks = Array.from(this.chunks.values())
.filter(chunk => {
const document = this.documentService.getById(chunk.documentId, user);
return document !== null; // Permission check!
});
return this.findSimilar(queryEmbedding, accessibleChunks);
}
}
Features:
- โ Documents filtered BEFORE embedding generation
- โ RAG retrieval respects user permissions
- โ Department-based document filtering
- โ Role-based access levels
- โ No data leakage between departments
Why This Matters:
The AI never sees documents the user isn't authorized to access. The RAG pipeline is permission-aware at every step, ensuring zero-knowledge of restricted content.
4. ๐ Complete Audit Trail
Bonus Feature: Track all AI agent actions for compliance
Implementation:
// Audit logging with deduplication
export class AuditService {
log(entry: AuditEntry): void {
// Deduplicate identical actions within 2 seconds
const dedupeKey = `${entry.userId}-${entry.action}-${entry.resourceType}`;
if (this.recentEntries.get(dedupeKey) > Date.now() - 2000) {
return; // Skip duplicate
}
this.logs.push({
...entry,
id: generateId(),
timestamp: new Date()
});
}
}
// Department-filtered audit access
if (user.role === UserRole.MANAGER) {
logs = logs.filter(log =>
log.metadata?.userDepartment === user.department
);
}
Features:
- โ Logs every AI query with document sources
- โ Tracks document access with user details
- โ Department-filtered for managers
- โ Deduplication prevents spam
- โ User-friendly display (names, not IDs)
Technical Architecture
Tech Stack
- Framework: Next.js 14 with TypeScript (App Router)
- Authentication: Auth0 for AI Agents
- AI Model: OpenRouter (Llama 3.2 3B Instruct - Free Tier)
- Styling: Tailwind CSS with custom components
Key Features
1. Role-Based Access Control (RBAC)
export function canAccessDocument(user: User, document: Document): boolean {
if (user.role === UserRole.ADMIN) return true;
if (user.role === UserRole.GUEST) return false;
if (!document.accessLevel.includes(user.role)) return false;
if (document.department === Department.ALL) return true;
return user.department === document.department;
}
2. Permission-Aware RAG Pipeline
- Documents chunked into 500-character segments
- Hash-based embeddings (no API quota limits)
- Cosine similarity search
- Title matching boost for better relevance
3. Smart Audit Logging
- Deduplication (no duplicate entries)
- Department filtering for managers
- User-friendly error messages
- Metadata includes user names and departments
Lessons Learned and Takeaways
๐ Key Insights
1. Security-First AI Design
The biggest lesson: AI agents need permission-aware data pipelines, not just API authentication.
It's not enough to authenticate the user - you must filter the AI's knowledge base based on user permissions. This required:
- Implementing RBAC at the RAG level
- Filtering documents before embedding generation
- Permission checks at every data access point
2. The Power of Auth0 for AI Agents
Auth0's approach to AI agent security is brilliant:
- User Authentication: Establishes who is prompting the agent
- Token Vault: Manages AI service credentials securely
- Fine-Grained Authorization: Enables permission-aware RAG
This three-layer approach ensures both the user AND the AI agent are properly secured.
3. RAG Authorization is Critical
Traditional RAG implementations often overlook permissions. I learned that:
- Documents must be filtered BEFORE embedding
- Query results must respect user access levels
- Audit trails must track what the AI accessed
4. UX Matters for Security
Security features need good UX:
- Clear error messages ("Access Restricted" vs "Error 403")
- Visual feedback (clickable examples, hover states)
- Intuitive navigation (bubble-style menu)
- Markdown rendering for better readability
๐ง Challenges Faced
Challenge 1: Gemini API Quota Limits
- Problem: Google Gemini free tier has strict embedding quotas
- Solution: Switched to OpenRouter (Llama 3.2) with hash-based embeddings
- Learning: Always have a fallback AI provider
Challenge 2: Guest Role Permissions
-
Problem: Guest users with
department: ALL
bypassed filters - Solution: Explicit role checks before department checks
- Learning: Permission logic order matters!
Challenge 3: Duplicate Audit Entries
- Problem: React's double-render caused duplicate logs
- Solution: Deduplication with time-based tracking
- Learning: In-memory state needs careful management
Challenge 4: Manager Audit Visibility
- Problem: Managers couldn't see team activity
- Solution: Department-filtered logs (not user-filtered)
- Learning: Audit requirements vary by role
๐ก Key Takeaways
For Developers Building AI Agents:
-
Implement Permission-Aware RAG
- Filter data before AI sees it
- Never trust the AI to enforce permissions
- Audit what the AI accesses
-
Use Auth0 for AI Agents Properly
- Authenticate the human user
- Manage AI service credentials securely
- Apply fine-grained authorization to data
-
Design for Compliance
- Audit trails are not optional
- Department filtering enables privacy
- User-friendly logs aid investigations
-
Test with Multiple Roles
- Create test users for each role
- Verify different access levels
- Ensure no data leakage
๐ฏ What I'm Proud Of
- Zero Data Leakage: Guests see 0 documents, employees see limited docs, managers see department docs
- Smart Audit Trail: Deduplication, department filtering, user names (not IDs)
- Professional UI: Minimalism design with perfect UX
- Production-Ready: Proper error handling, markdown rendering, clickable examples
Conclusion
SecureDoc AI Assistant demonstrates that AI agents can be both powerful and secure.
By implementing Auth0 for AI Agents with permission-aware RAG, we created a system where:
- Users get intelligent answers from AI
- AI only accesses authorized documents
- Every action is audited for compliance
- Different roles have appropriate access levels
The future of AI agents is secure, permission-aware, and auditable.
๐ Acknowledgments
Built for the Auth0 AI Agents Challenge. Special thanks to the Auth0 team for creating such a comprehensive framework for securing AI agents!
Top comments (0)