secure_session_manager 1.0.2 copy "secure_session_manager: ^1.0.2" to clipboard
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_storage for 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 IdleController and LifecycleObserver are only created if configured.
  • Mutex Locking: Uses the synchronized package 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

2
likes
160
points
102
downloads

Publisher

verified publishergreelogix.com

Weekly Downloads

A lightweight, secure, and highly scalable session management package for Flutter with zero performance overhead when optional features are disabled.

Homepage
Repository (GitHub)
View/report issues

Topics

#session #authentication #token #security #storage

Documentation

API reference

License

MIT (license)

Dependencies

clock, flutter, flutter_secure_storage, meta, synchronized

More

Packages that depend on secure_session_manager