7.2 KiB
SSO (Single Sign-On) Implementation for Spotizerr
Overview
I have successfully implemented comprehensive SSO backend logic for Google and GitHub authentication in your Spotizerr application. This implementation integrates seamlessly with your existing JWT-based authentication system.
What Was Implemented
1. Dependencies Added
- Added
fastapi-sso==0.18.0torequirements.txt
2. New Files Created
routes/auth/sso.py- Complete SSO implementation with Google & GitHub supportroutes/auth/sso_example.py- Example client for testing SSO functionalitySSO_IMPLEMENTATION.md- This documentation file
3. Updated Files
routes/auth/__init__.py- Extended User model to support SSO fieldsroutes/auth/auth.py- Updated authentication status to include SSO inforoutes/auth/middleware.py- Added SSO endpoints to public pathsAUTH_SETUP.md- Comprehensive SSO setup documentationrequirements.txt- Added fastapi-sso dependency
4. Extended User Model
The User class now supports:
sso_provider- Which SSO provider was used (google/github)sso_id- Provider-specific user IDis_sso_user- Boolean flag for frontend use
Environment Configuration
Create a .env file with the following variables:
# Basic Authentication
ENABLE_AUTH=true
JWT_SECRET=your-super-secret-jwt-key-change-in-production
JWT_EXPIRATION_HOURS=24
DEFAULT_ADMIN_USERNAME=admin
DEFAULT_ADMIN_PASSWORD=your-secure-password
# SSO Configuration
SSO_ENABLED=true
SSO_BASE_REDIRECT_URI=http://localhost:8000/api/auth/sso/callback
FRONTEND_URL=http://localhost:3000
# Google SSO (optional)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
# GitHub SSO (optional)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-client-secret
API Endpoints Added
SSO Status & Information
GET /api/auth/sso/status- Get SSO configuration and available providers
Google SSO
GET /api/auth/sso/login/google- Initiate Google OAuth flowGET /api/auth/sso/callback/google- Handle Google OAuth callback (automatic)
GitHub SSO
GET /api/auth/sso/login/github- Initiate GitHub OAuth flowGET /api/auth/sso/callback/github- Handle GitHub OAuth callback (automatic)
SSO Management
POST /api/auth/sso/unlink/{provider}- Unlink SSO provider from user account
Enhanced Authentication Status
GET /api/auth/status- Now includes SSO status and available providers
OAuth Provider Setup
Google SSO Setup
- Go to Google Cloud Console
- Create a new project or select existing one
- Enable Google+ API
- Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client IDs"
- Configure OAuth consent screen
- Set authorized redirect URIs:
- Development:
http://localhost:8000/api/auth/sso/callback/google - Production:
https://yourdomain.com/api/auth/sso/callback/google
- Development:
- Copy Client ID and Client Secret to environment variables
GitHub SSO Setup
- Go to GitHub Settings → Developer settings → OAuth Apps
- Click "New OAuth App"
- Fill in application details:
- Application name: Your app name
- Homepage URL: Your app URL
- Authorization callback URL:
- Development:
http://localhost:8000/api/auth/sso/callback/github - Production:
https://yourdomain.com/api/auth/sso/callback/github
- Development:
- Copy Client ID and Client Secret to environment variables
How It Works
SSO Flow
- User clicks "Login with Google/GitHub" button in frontend
- Frontend redirects to
/api/auth/sso/login/{provider} - User is redirected to provider's OAuth consent screen
- After consent, provider redirects to
/api/auth/sso/callback/{provider} - Backend validates OAuth code and retrieves user info
- System creates or updates user account
- JWT token is generated and set as HTTP-only cookie
- User is redirected to frontend with authentication complete
User Management
- New SSO Users: Automatically created with
userrole (first user getsadmin) - Existing Users: SSO provider linked to existing account by email
- Username Generation: Uses email prefix, ensures uniqueness
- Password: SSO users have
password_hash: null(cannot use password login)
Testing the Implementation
1. Install Dependencies
pip install fastapi-sso==0.18.0
2. Configure Environment
Set up your .env file with the OAuth credentials from Google/GitHub
3. Start the Application
uvicorn app:app --reload
4. Test SSO Status
curl http://localhost:8000/api/auth/sso/status
5. Test Authentication Flow
- Visit
http://localhost:8000/api/auth/sso/login/googlein browser - Complete OAuth flow
- Should redirect to frontend with authentication
6. Programmatic Testing
Run the example script:
python routes/auth/sso_example.py
Security Features
Production Ready
- HTTPS Support: Set
allow_insecure_http=Falsein production - Secure Cookies: HTTP-only cookies with secure flag
- CORS Configuration: Properly configured for your frontend domain
- Token Validation: Full server-side JWT validation
- Provider Verification: Validates OAuth responses from providers
OAuth Security
- State Parameter: CSRF protection in OAuth flow
- Redirect URI Validation: Strict redirect URI matching
- Token Expiration: Configurable JWT token expiration
- Provider Validation: Ensures tokens come from legitimate providers
Integration Points
Frontend Integration
The authentication status endpoint now returns SSO information:
{
"auth_enabled": true,
"sso_enabled": true,
"sso_providers": ["google", "github"],
"authenticated": false,
"user": null,
"registration_enabled": true
}
User Data Structure
SSO users have additional fields:
{
"username": "john_doe",
"email": "john@example.com",
"role": "user",
"sso_provider": "google",
"is_sso_user": true,
"created_at": "2024-01-15T10:30:00",
"last_login": "2024-01-15T10:30:00"
}
Error Handling
The implementation includes comprehensive error handling for:
- Missing OAuth credentials
- OAuth flow failures
- Provider-specific errors
- Invalid redirect URIs
- Network timeouts
- Invalid tokens
Backwards Compatibility
- Existing Users: Unaffected, can still use password authentication
- Existing API: All existing endpoints work unchanged
- Configuration: SSO is optional, system works without it
- Database: Extends existing user storage, no migration needed
Next Steps
- Configure OAuth Apps: Set up Google and GitHub OAuth applications
- Update Frontend: Add SSO login buttons that redirect to SSO endpoints
- Test Flow: Test complete authentication flow end-to-end
- Production Setup: Configure HTTPS and production redirect URIs
- User Management: Add SSO management to your admin interface
Support
The implementation follows FastAPI best practices and integrates cleanly with your existing authentication system. All SSO functionality is optional and gracefully degrades if not configured.
For issues or questions, check the comprehensive documentation in AUTH_SETUP.md or refer to the example client in routes/auth/sso_example.py.