Why Use flutter_secure_storage Over shared_preferences for Storing PII in Flutter Apps
When building Flutter apps, securely storing sensitive information like Personally Identifiable Information (PII) and authentication tokens is essential. While shared_prefernces
is commonly used for key-value storage, it doesn’t offer the encryption or security needed for sensitive data. Data stored in `shared_preferences` is saved in plain text, making it vulnerable to unauthorized access if the device is compromised.
Why Not Use shared_preferences?
shared_prefernces
is ideal for storing non-sensitive data, such as user preferences and settings, but it’s not secure for PII or tokens.
Sensitive data stored here can be accessed if someone gains access to the device, as shared_prefernces
lacks encryption.
Why flutter_secure_storage Is Better for PII and Tokens
flutter_secure_storage
is designed to securely store sensitive information by using:
- iOS Keychain for iOS and Android Keystore for Android, offering strong encryption.
- Automatic integration with platform security updates, which enhances data protection over time.
This makes flutter_secure_storage
a better choice for securely storing items like user emails and auth tokens.
Quick Setup with flutter_secure_storage
- Add
flutter_secure_storage
topubspec.yaml
:
dependencies:
flutter_secure_storage: ^8.0.0
- Import and Use:
dart
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
final storage = FlutterSecureStorage();
// Store email and auth token
await storage.write(key: 'userEmail', value: 'user@example.com');
await storage.write(key: 'authToken', value: 'your_auth_token');
// Retrieve email and auth token
String? email = await storage.read(key: 'userEmail');
String? token = await storage.read(key: 'authToken');
// Delete sensitive data when no longer needed
await storage.delete(key: 'userEmail');
await storage.delete(key: 'authToken');
Best Practices
- Store Only Essential PII: Minimize stored PII and tokens to only what is necessary.
- Clear Data When Not Needed: Delete sensitive data when it’s no longer required.
- Use Biometrics for Extra Security: Combine
flutter_secure_storage
withlocal_auth
to prompt for biometrics before accessing sensitive data.
Conclusion
For secure storage of PII and tokens, flutter_secure_storage
is far safer than shared_prefernces
. It leverages encryption and secure storage mechanisms native to iOS and Android, providing a reliable solution for protecting user data in your Flutter app.