What's the best way to save jwt tokens in flutter apps?
You probably don't want to store sensitive data in shared preferences. Instead you might want to look into a plugin like this: https://pub.dartlang.org/packages/flutter_secure_storage
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// Create storage
final storage = new FlutterSecureStorage();
// Write value
await storage.write(key: 'jwt', value: token);
As I mentioned on a deleted post, I've been using hive to storage my tokens and other local data. With hive it's possible to create an encrypted box
import 'dart:typed_data';
import 'package:hive/hive.dart';
void main() async {
var keyBox = await Hive.openBox('encryptionKeyBox');
if (!keyBox.containsKey('key')) {
var key = Hive.generateSecureKey();
keyBox.put('key', key);
}
var key = keyBox.get('key') as Uint8List;
print('Encryption key: $key');
var encryptedBox = await Hive.openBox('vaultBox', encryptionKey: key);
encryptedBox.put('secret', 'Hive is cool');
print(encryptedBox.get('secret'));
}
As mentioned in comments:
The example above stores the encryption key in an unencrypted box. You should NEVER do that.
Important:
- Only values are encrypted while keys are stored in plaintext.
- Make sure to store the encryption key securely when your application is closed. With Flutter you can use the flutter_secure_storage or a similar package.
- There is no check if the encryption key is correct. If it isn't, there may be unexpected behavior.
So, if you don't need any of
hive
specific features, flutter_secure_storage should be a better option for you.