Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to save jwt tokens in flutter apps?

Tags:

token

jwt

flutter

Not just where (eg: SQLite...) but also how (libs, best specific practices)?

like image 219
zeucxb Avatar asked Mar 07 '19 03:03

zeucxb


People also ask

Where do I save JWT token flutter?

import 'package:flutter_secure_storage/flutter_secure_storage. dart'; // Create storage final storage = new FlutterSecureStorage(); // Write value await storage. write(key: 'jwt', value: token);

What is the best way to store JWT token react?

Storing JWT Token We need to store this token somewhere. We can store it as a client-side cookie or in a localStorage or sessionStorage. There are pros and cons in each option but for this app, we'll store it in sessionStorage. //persisted across tabs and new windows.

Where should I store my JWT token?

To keep them secure, you should always store JWTs inside an httpOnly cookie. This is a special kind of cookie that's only sent in HTTP requests to the server. It's never accessible (both for reading or writing) from JavaScript running in the browser.


2 Answers

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); 
like image 151
Nicodemuz Avatar answered Sep 18 '22 18:09

Nicodemuz


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.

like image 35
zeucxb Avatar answered Sep 21 '22 18:09

zeucxb