Using Secure Storage in Flutter

Photo by Dan Nelson on Unsplash

Using Secure Storage in Flutter

Hey guys, lemme share with you why I started using Flutter Secure Storage in the first place. So initially I used SharedPreference for storing all the API keys but when switched to custom backend from Firebase, I searched for how to save sensitive data using this package. But luckily, I was introduced to Secure Storage in Flutter. And here we'll discuss everything in and out about this package.

What is Flutter Secure Storage ?

Flutter Secure Storage is used to store all the sensitive data of the flutter application. As mentioned in flutter_secure_storage, the data is stored in Keychain for iOS and Keystore for Android (i.e. encryptedSharedPreference) which makes it safer to store all the critical data. It uses AES encryption for Android. You can read more about it in the documentation

Why not use SharedPreferences then ?

I'll discuss this package later on in a separate article. But in a nutshell, SharedPreferences is used for storing simple key-pair values. It is not a safe option for storing private data because it can be accessed at the root level (Read Android SharedPreference security for more clarity) as also mentioned in shared_preferences.

Setting up the package

Add the dependency in the pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  flutter_secure_storage: "<latest-version>"

Then import the package in the file you want to implement it in.

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

Functions for storing and deleting data

Let's use this package for checking the user login session. If the user stays inactive for 2 days, the login session will be expired. So we'll create a class named SessionStorage to check the login time validity of the user.

class SessionStorage{
 final FlutterSecureStorage flutterSecureStorage =
      const FlutterSecureStorage();
}

After initializing this object, we'll use it to store the time when the user gets logged in.

  // this is the the function to write new the timestamp in the memory.
  void writeCurrentSessionTime() {
    flutterSecureStorage.write(
        key: 'SessionCreatedAt', value: DateTime.now().toString());
  }

Now, add the functions to read and delete the timestamp:

  //this is the function to read the previous timestamp in the storage.
  Future<String?> readPreviousSessionTime() async {
    final String? value =
        await flutterSecureStorage.read(key: 'SessionCreatedAt');
    return value;
  }

  //this is the function to write the new timestamp in the storage.
  Future<void> deleteSessionKey() async {
    await flutterSecureStorage.delete(key: 'SessionCreatedAt');
  }

The final code for the SessionStorage class will now become:

class SessionStorage{
 final FlutterSecureStorage flutterSecureStorage =
      const FlutterSecureStorage();

  // this is the the function to write the new timestamp in the memory.
  void writeCurrentSessionTime() {
    flutterSecureStorage.write(
        key: 'SessionCreatedAt', value: DateTime.now().toString());
  }

  //this is the function to read the previous timestamp in the storage.
  Future<String?> readPreviousSessionTime() async {
    final String? value =
        await flutterSecureStorage.read(key: 'SessionCreatedAt');
    return value;
  }

  //this is the function to write the new timestamp in the storage.
  Future<void> deleteSessionKey() async {
    await flutterSecureStorage.delete(key: 'SessionCreatedAt');
  }
}

Using the above methods in the app

Firstly we'll create an instance of the above class.

SessionStorage _sessionStorage = SessionStorage();

After that, we'll store the user login time.

 _sessionStorage.writeCurrentSessionTime();

Then, for checking the session validity after 2 days:

Future<void> checkForExpiredSession() async {
    final String? value = await _sessionStorage.readPreviousSessionTime();
    if (value != null) {
      final int diff = DateTime.now().difference(DateTime.parse(value)).inDays;

      if (diff >= 2) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
          content: Text('Session Expired!'),
          backgroundColor: Colors.black,
        ));
            await FirebaseAuth.instance.signOut();
            await _sessionStorage.deleteSessionKey();
      }
    }
  }

The session key will be deleted if there's no login within 2 days and the user will have to login again.

Conclusion

As you have seen one of the applications of flutter_secure_storage, you can now use it to store API keys, user credentials, or any other sensitive data for your flutter app.

Hope you liked this article. Thanks for reading❤