Authentication in micro frontend architectures presents unique challenges compared to traditional monolithic applications. Here’s a comprehensive approach to handling authentication:
Common Approaches
1. Shared Authentication Module
- Create a shared auth library/package used by all micro frontends
- Implements common auth logic (token validation, user info fetching)
- Ensures consistency across all applications
2. Container-Based Authentication
- The shell/container application handles authentication
- Once authenticated, it passes tokens/user info to child micro frontends
- Child apps trust the container’s auth state
3. Central Auth Service
- Dedicated authentication microservice
- All micro frontends communicate with this service
- Can implement OAuth/OpenID Connect flows
Implementation Patterns
Token Management
- JWT (JSON Web Tokens) most common
- Store tokens in:
- HTTP-only cookies (most secure)
- Session storage (for SPAs)
- Local storage (less secure but persistent)
- Implement token refresh logic
Cross-Origin Considerations
- For micro frontends on different domains:
- Use CORS properly configured
- Consider OAuth with PKCE for public clients
- Set
SameSite
cookie attributes appropriately
Session Synchronization
- Use a shared session store (Redis)
- Implement silent authentication iframes
- Broadcast auth state changes via:
- Custom events
- Shared state management (Redux, Zustand)
- Window.postMessage()
Security Best Practices
- Never store sensitive tokens in localStorage
- Use short-lived access tokens + refresh tokens
- Implement proper CORS headers
- Validate tokens in each micro frontend
- Secure communication with HTTPS only
- Implement CSRF protection for cookie-based auth
Framework-Specific Solutions
- React: Use Context API or state management libraries
- Angular: Implement an AuthGuard and shared service
- Vue: Use Vuex/Pinia for shared auth state
Example Flow
- User accesses container app
- Container checks auth status:
- If not authenticated, redirects to login
- If authenticated, loads micro frontends
- Micro frontends receive auth tokens via props or API
- Each micro frontend validates its own tokens
- On token expiration, coordinated refresh occurs