secure_session_manager
A lightweight, secure, and highly scalable session management package for Flutter apps with zero performance overhead when optional features are disabled.
Features
- ๐ Secure Storage: Uses
flutter_secure_storagefor persisting tokens. - ๐ Performance: In-memory caching for sub-millisecond token access.
- ๐ Atomic Refresh: Automatic token refresh with a mutex to prevent multiple simultaneous refresh calls.
- ๐ฆ Request Queueing: Queues pending requests during an active token refresh.
- โณ Idle Timeout: Optional, event-driven idle detection (no polling).
- ๐ฑ App Lifecycle: Automatically validates session on app resume.
- ๐ Interceptors: Pre-built
Dioandhttpinterceptors for automatic token injection and 401 handling. - ๐งฉ JWT Support: Automatic expiry detection from JWT payloads.
- ๐ฆ Flexible Storage: Use
SecureStorageProvider(default) orSharedPreferencesProvider. - ๐งช Testable: Designed with dependency injection for easy unit testing.
- ๐ Zero Overhead: Optional features are only instantiated if enabled.
Installation
Add to your pubspec.yaml:
dependencies:
secure_session_manager: ^1.1.0
Usage
1. Implement TokenProvider
Implement this interface to define how your app refreshes its authentication tokens.
class MyTokenProvider implements TokenProvider {
@override
Future<SessionToken> refreshToken(SessionToken currentToken) async {
// Call your API to refresh the token
return SessionToken(
accessToken: 'new_access_token',
refreshToken: 'new_refresh_token',
expiresAt: DateTime.now().add(Duration(hours: 1)),
);
}
}
2. Initialize SessionManager
Initialize the singleton at the start of your app.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SessionManager.instance.initialize(
tokenProvider: MyTokenProvider(),
// Optional: Use SharedPreferences instead of SecureStorage
storageProvider: SharedPreferencesProvider(),
);
runApp(MyApp());
}
3. Networking Interceptors
The package provides built-in interceptors for Dio and http that automatically:
- Inject the
Authorization: Bearer <token>header. - Intercept
401 Unauthorizederrors. - Trigger a token refresh and replay the failed request seamlessly.
For Dio
final dio = Dio();
dio.interceptors.add(SecureSessionDioInterceptor(dio));
For http package
final client = SecureSessionHttpInterceptor(http.Client());
// Use 'client' instead of 'http' for your requests
4. JWT Automatic Expiry
If your accessToken is a JWT, the package can automatically extract the exp claim.
final token = SessionToken(accessToken: "your.jwt.token");
print(token.expiresAt); // Automatically parsed if not provided
5. Manual Session Control
// Save session on login
await SessionManager.instance.setSession(token);
// Get current token (auto-refreshes if expired)
final token = await SessionManager.instance.getAccessToken();
// Logout / Clear session
await SessionManager.instance.logout();
Advanced Features
Idle Detection
To detect when a user is idle and automatically log them out.
await SessionManager.instance.initialize(
tokenProvider: MyTokenProvider(),
idleTimeout: Duration(minutes: 15),
);
// In your main build method
return Listener(
onPointerDown: (_) => SessionManager.instance.touch(),
behavior: HitTestBehavior.translucent,
child: MaterialApp(...),
);
Listen to Events
SessionManager.instance.onSessionExpired.listen((_) => goToLogin());
SessionManager.instance.onLogout.listen((_) => cleanup());
Performance-First Design
- Lazy Initialization: Components like
IdleControllerandLifecycleObserverare only created if configured. - Mutex Locking: Ensures that even if 100 concurrent requests trigger a refresh, only one network call is made.
- In-Memory Cache: Tokens are cached in RAM after the first read from storage.
โค๏ธ Maintained By
GreenLogix โ Flutter, Laravel & AI Development Agency
๐ https://greelogix.com
๐ฉ hello@greelogix.com
๐ฆ Other Open-Source Flutter Packages by GreenLogix
Check out our other packages like Launchify, Best Form Validator, and Flutter Telescope.
License
MIT