Skip to content

v0.4.0: Authentication & Authorization System#13

Merged
KeshavVarad merged 4 commits intomainfrom
feature/v0.4.0-auth
Nov 4, 2025
Merged

v0.4.0: Authentication & Authorization System#13
KeshavVarad merged 4 commits intomainfrom
feature/v0.4.0-auth

Conversation

@KeshavVarad
Copy link
Copy Markdown
Owner

Summary

This PR implements a complete authentication and authorization system for NextMCP v0.4.0, inspired by next-auth and adapted for the Model Context Protocol.

🔐 What's New

Core Auth Framework

  • AuthContext: Authentication context with user info, roles, and permissions
  • AuthProvider: Base class for implementing custom auth strategies
  • AuthResult: Authentication result with success/failure handling
  • Permission: Fine-grained permission model with wildcard support (admin:*, *)
  • Role: Role class with permission collections

Built-in Auth Providers

1. APIKeyProvider

  • Pre-configured API key validation
  • Custom validation function support
  • Secure key generation utility
  • Role and permission mapping per key

2. JWTProvider

  • JWT token creation and verification
  • HS256/RS256 algorithm support
  • Automatic expiration validation
  • Custom claims support
  • Requires PyJWT (optional dependency)

3. SessionProvider

  • In-memory session storage
  • Automatic session expiration
  • Session creation and destruction
  • Expired session cleanup

RBAC System

  • RBAC class for role and permission management
  • Define custom permissions and roles
  • Assign permissions to roles
  • Check and require permissions/roles on tools
  • Load configuration from dictionaries
  • Export configuration for persistence
  • PermissionDeniedError exception

Auth Middleware

  • @requires_auth / @requires_auth_async - Require authentication
  • @requires_role / @requires_role_async - Require specific roles
  • @requires_permission / @requires_permission_async - Require specific permissions
  • Auth context automatically injected as first parameter
  • Full middleware stacking support

📚 Examples

Three complete examples with comprehensive READMEs:

  1. examples/auth_api_key/ - API key authentication with role-based access control
  2. examples/auth_jwt/ - JWT token authentication with login endpoint and token generator
  3. examples/auth_rbac/ - Advanced RBAC with fine-grained permissions and wildcards

🧪 Tests

62 new tests, all passing:

  • test_auth_providers.py: 26 tests covering all 3 providers
  • test_rbac.py: 36 tests for RBAC system

Total: 297/297 tests passing (235 original + 62 new)

📖 Documentation

  • ✅ Comprehensive README section (~400 lines of auth documentation)
  • ✅ Quick start examples for each provider
  • ✅ RBAC usage guide
  • ✅ Permission wildcards documentation
  • ✅ AuthContext API reference
  • ✅ Middleware stacking examples
  • ✅ Session management guide
  • ✅ Custom auth provider template
  • ✅ Error handling examples
  • ✅ Security best practices
  • ✅ Updated CHANGELOG with detailed release notes
  • ✅ Updated comparison table with auth features
  • ✅ Roadmap marked v0.4.0 as completed

🔄 Integration

  • All 15 auth classes exported in nextmcp/__init__.py
  • Version bumped from 0.3.0 to 0.4.0
  • pyproject.toml updated
  • 100% backward compatible

💡 Usage Example

from nextmcp import NextMCP
from nextmcp.auth import APIKeyProvider, AuthContext, requires_auth_async

app = NextMCP("secure-server")

# Configure auth
api_key_provider = APIKeyProvider(
    valid_keys={
        "admin-key": {"user_id": "admin1", "roles": ["admin"]}
    }
)

# Protected tool
@app.tool()
@requires_auth_async(provider=api_key_provider)
async def protected_tool(auth: AuthContext, data: str) -> dict:
    return {"user": auth.username, "data": data}

✅ Checklist

  • Core auth framework implemented
  • 3 auth providers (API Key, JWT, Session)
  • Complete RBAC system
  • Auth middleware decorators
  • 62 comprehensive tests (all passing)
  • 3 complete examples with READMEs
  • README documentation (~400 lines)
  • CHANGELOG updated
  • Version bumped to 0.4.0
  • All 297 tests passing
  • 100% backward compatible
  • Exports added to __init__.py

🎯 Key Benefits

  1. Production-Ready: Complete auth system with 3 providers and RBAC
  2. Flexible: Support for API keys, JWT, sessions, and custom providers
  3. Fine-Grained: Permission-based access control with wildcards
  4. Developer-Friendly: Simple decorator-based API
  5. Well-Tested: 62 comprehensive tests
  6. Well-Documented: Extensive docs and 3 complete examples
  7. Backward Compatible: All existing tests pass

📊 Test Results

297 passed in 5.14s

All original tests (235) + new auth tests (62) = 100% passing

🔒 Security

  • Never commit secrets (documented in README)
  • Secure key generation utilities
  • Token expiration support
  • Session timeout handling
  • Security best practices documented

🤖 Generated with Claude Code

Keshav Varadarajan and others added 4 commits November 4, 2025 14:01
Implement production-grade authentication and authorization system
inspired by next-auth, adapted for the Model Context Protocol.

Core Features:
- Complete auth framework with AuthContext, AuthProvider, AuthResult
- Permission and Role classes with wildcard support
- 3 built-in auth providers (API Key, JWT, Session)
- Full RBAC system with fine-grained permissions
- 6 auth middleware decorators (sync/async variants)
- Custom auth provider support

Auth Providers:
- APIKeyProvider: Pre-configured keys, custom validators, secure generation
- JWTProvider: Token creation/verification, expiration handling (requires PyJWT)
- SessionProvider: In-memory sessions, automatic cleanup, expiration

RBAC System (nextmcp/auth/rbac.py):
- Define and manage roles and permissions
- Permission wildcards (admin:*, *)
- Load configuration from dictionaries
- Check and require permissions/roles
- PermissionDeniedError exception

Auth Middleware (nextmcp/auth/middleware.py):
- @requires_auth / @requires_auth_async
- @requires_role / @requires_role_async
- @requires_permission / @requires_permission_async
- Auth context injection as first parameter
- Middleware stacking support

Examples:
- examples/auth_api_key/: API key auth with role-based access
- examples/auth_jwt/: JWT auth with token generator utility
- examples/auth_rbac/: Advanced RBAC with permission wildcards

Tests (62 new, all passing):
- test_auth_providers.py: 26 tests for all 3 providers
- test_rbac.py: 36 tests for RBAC system
- Total: 297/297 tests passing (100% backward compatible)

Documentation:
- Comprehensive README auth section (~400 lines)
- Quick start examples for each provider
- RBAC usage guide with wildcards
- AuthContext, middleware, session management docs
- Security best practices
- 3 complete examples with READMEs

Integration:
- All 15 auth classes exported in nextmcp/__init__.py
- Version bumped to 0.4.0
- CHANGELOG updated with detailed release notes
- Updated comparison table and roadmap

100% backward compatible - all 235 original tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fix linting issues in v0.4.0 auth implementation:

Ruff fixes:
- Remove unused imports (asyncio, typing.Optional, etc.)
- Organize import statements
- Prefix unused variables with underscore (_session1, etc.)
- Add "from err" to ImportError raise in JWTProvider
- Auto-fix import sorting across all files

Black formatting:
- Format nextmcp/auth/middleware.py
- Format examples/auth_rbac/server.py
- Format tests/test_auth_providers.py
- Format tests/test_rbac.py

All 297 tests still passing after linting fixes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Fix remaining linting issues caught by pre-commit hook:

- examples/async_weather_bot/app.py: Remove unused batch_weather variable
- examples/knowledge_base/app.py: Convert generator to set comprehension
- examples/metrics_example/app.py: Rename unused loop variable to _i
- examples/websocket_chat/client.py: Remove unused results variable
- examples/websocket_chat/server.py: Convert generator to set comprehension

All auto-fixed by ruff with --unsafe-fixes flag.
All 297 tests still passing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Add pre-commit hook to enforce code quality automatically:

Features:
- Runs ruff linting with auto-fix before each commit
- Applies black formatting automatically
- Runs full test suite to prevent breaking changes
- Blocks commits that fail linting or tests
- Auto-fixes applied but require manual review/staging

Installation:
- Hook stored in tracked `hooks/pre-commit`
- Install script: `./scripts/install-hooks.sh`
- Documented in README Development section

Benefits:
- Prevents linting failures in CI
- Ensures consistent code formatting
- Catches test failures before push
- Saves review time by enforcing quality locally

Hook runs automatically on `git commit`.
Bypass with `git commit --no-verify` (not recommended).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@KeshavVarad KeshavVarad merged commit 5d6425b into main Nov 4, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant