Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to access secure storage every API request in Flutter?

Tags:

flutter

dart

In my flutter application, I store JWT using flutter_secure_storage. And I need to send the token every API request.

QUESTION1 If I access flutter_secure_storage every API request like below, there are any performance or security problems? I worry about to be await for access flutter_secure_storage.

Future<http.Response> getRequest(String url) async {
  String token = await FlutterSecureStorage().read(key: 'token');
  return await http.get(url, headers: {'token': token});
}

QUESTION2 Is it a good way to create a singleton class which has a token like below? In the code, I don't access flutter_secure_storage every API request. So I think the performance improve a little.

// singleton class which has token.
class Auth {
  final String _token;

  String get token => _token;

  static Auth _instance;

  factory Auth() => _instance;

  Auth._init(this._token);

  static Future<void> create() async {
    String token = await FlutterSecureStorage().read(key: 'token');
    _instance = Auth._init(token);
  }
}

// initialize singleton class in main
void main() async {
  await Auth.create();
  runApp(MyApp());
}
// able to get the token anywhere without await
Future<http.Response> getRequest(String url) async {
  String token = Auth().token;
  return await http.get(url, headers: {'token': token});
}

Please tell me best way.

like image 677
Tauyori Avatar asked Mar 23 '20 15:03

Tauyori


1 Answers

I think the best way is to create a Secure Storage Singleton like I did here for SharedPreferences

    import 'package:shared_preferences/shared_preferences.dart';
class StorageUtil {
  static StorageUtil _storageUtil;
  static SharedPreferences _preferences;

  static Future<StorageUtil> getInstance() async {
    if (_storageUtil == null) {
      // keep local instance till it is fully initialized.
      var secureStorage = StorageUtil._();
      await secureStorage._init();
      _storageUtil = secureStorage;
    }
    return _storageUtil;
  }
  StorageUtil._();
  Future _init() async {
    _preferences = await SharedPreferences.getInstance();
  }
  // get string
  static String getString(String key, {String defValue = ''}) {
    if (_preferences == null) return defValue;
    return _preferences.getString(key) ?? defValue;
  }
  // put string
  static Future<bool> putString(String key, String value) {
    if (_preferences == null) return null;
    return _preferences.setString(key, value);
  }

}

You'll need to call the instance in your main file.

void main() async {    
  await StorageUtil.getInstance();
}

You will be able to get the token anywhere as

StorageUtil.getString("token");
like image 87
Tayormi Avatar answered Nov 15 '22 05:11

Tayormi