secure_session_manager 1.0.2
secure_session_manager: ^1.0.2 copied to clipboard
A lightweight, secure, and highly scalable session management package for Flutter with zero performance overhead when optional features are disabled.
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.
- ๐งช Testable: Designed with dependency injection for easy unit testing.
- ๐ Zero Overhead: Optional features (idle timeout, lifecycle) are only instantiated if enabled.
Installation #
Add to your pubspec.yaml:
dependencies:
secure_session_manager:
path: ../ # If using locally or use git/pub version
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
// Final response should be a new SessionToken
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(),
idleTimeout: Duration(minutes: 30), // Optional
);
runApp(MyApp());
}
3. Usage in App #
Save Session on Login
await SessionManager.instance.setSession(SessionToken(
accessToken: 'abc',
refreshToken: 'def',
expiresAt: DateTime.now().add(Duration(days: 1)),
));
Get Access Token
// Automatically refreshes if expired
final token = await SessionManager.instance.getAccessToken();
Idle Detection & Global Activity
To detect when a user is idle and automatically log them out, use the idleTimeout parameter during initialization. To reset the timer on any user interaction, wrap your MaterialApp with a Listener.
// main.dart
void main() async {
await SessionManager.instance.initialize(
tokenProvider: MyTokenProvider(),
idleTimeout: Duration(minutes: 15),
);
runApp(MyApp());
}
// App wrapper
Widget build(BuildContext context) {
return Listener(
onPointerDown: (_) => SessionManager.instance.touch(),
behavior: HitTestBehavior.translucent,
child: MaterialApp(
home: HomeScreen(),
),
);
}
Listen to Security Events
Stay informed about session changes globally.
// Listen for any session expiry (Idle timeout vs Explicit Token Expiry)
SessionManager.instance.onSessionExpired.listen((_) {
print("User has been idle too long!");
});
// Listen for global logouts
SessionManager.instance.onLogout.listen((_) {
navigatorKey.currentState?.pushNamedAndRemoveUntil('/login', (r) => false);
});
// Listen for successful refreshes
SessionManager.instance.onTokenRefreshed.listen((token) {
print('Token refreshed: ${token.accessToken}');
});
Performance-First Design #
- Lazy Initialization: Components like
IdleControllerandLifecycleObserverare only created if configured. - Mutex Locking: Uses the
synchronizedpackage to ensure 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 secure storage, avoiding expensive disk I/O on every request.
Testing #
The package is designed to be fully testable. You can inject mock collections of StorageProvider and TokenProvider during initialization.
await SessionManager.instance.initialize(
storageProvider: MockStorageProvider(),
tokenProvider: MockTokenProvider(),
);
โค๏ธ Maintained By #
GreenLogix โ Flutter, Laravel & AI Development Agency
๐ https://greelogix.com
๐ฉ hello@greelogix.com
Need custom Flutter development, package customization, or enterprise integrations? Weโd love to help.
๐ฆ Other Open-Source Flutter Packages by GreenLogix #
If you find Secure Session Manager useful for managing user sessions and tokens, you may also benefit from these Flutter packages:
๐น Launchify #
Production-ready URL launcher UI widgets for WhatsApp, Phone, Email, Maps, Social Apps & Deep Links.
๐ https://pub.dev/packages/launchify
๐น Best Form Validator #
A robust Flutter form validation library with ready-to-use validators and easy integration.
๐ https://pub.dev/packages/best_form_validator
๐น httpio_client #
A powerful, unified networking package for Flutter that handles token refresh, retries, logging, and offline queuing.
๐ https://pub.dev/packages/httpio_client
๐น Quick Popup Manager #
Smart popup, dialog, and overlay management for Flutter apps.
๐ https://pub.dev/packages/quick_popup_manager
๐น Smart Form Toolkit #
Advanced Flutter form toolkit with ready-to-use widgets, validation, and flexible field customization.
๐ https://pub.dev/packages/smart_form_toolkit
๐น Safe JSON Mapper #
Type-safe JSON parsing and mapping utilities for Flutter.
๐ https://pub.dev/packages/safe_json_mapper
๐น Flutter Telescope #
Advanced Flutter debugging, logging, and app insights toolkit.
๐ https://pub.dev/packages/flutter_telescope
โญ If Secure Session Manager helped you, consider exploring our other packages for faster, safer, and more productive Flutter development.
License #
MIT