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.


Using https://pub.dartlang.org/packages/shared_preferences is best for you, as it "provides a persistent store for simple data."

Sample code:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
      child: RaisedButton(
        onPressed: _getAndSaveToken,
        child: Text('Get token'),
        ),
      ),
    ),
  ));
}

_getAndSaveToken() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String token = await _getTokenFromHttp();
  await prefs.setInt('jwt', token);
}

Future<String> _getTokenFromHttp() async {
  // http code here
}

Tags:

Token

Jwt

Flutter