secure_session_manager 1.1.0 copy "secure_session_manager: ^1.1.0" to clipboard
secure_session_manager: ^1.1.0 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.
  • ๐ŸŒ Interceptors: Pre-built Dio and http interceptors for automatic token injection and 401 handling.
  • ๐Ÿงฉ JWT Support: Automatic expiry detection from JWT payloads.
  • ๐Ÿ“ฆ Flexible Storage: Use SecureStorageProvider (default) or SharedPreferencesProvider.
  • ๐Ÿงช 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:

  1. Inject the Authorization: Bearer <token> header.
  2. Intercept 401 Unauthorized errors.
  3. 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 IdleController and LifecycleObserver are 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

2
likes
160
points
103
downloads

Documentation

API reference

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

License

MIT (license)

Dependencies

clock, dio, flutter, flutter_secure_storage, http, meta, shared_preferences, synchronized

More

Packages that depend on secure_session_manager