簡體   English   中英

在顫振應用程序中保存 jwt 令牌的最佳方法是什么?

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

不僅僅是在哪里(例如:SQLite ...),還有如何(庫,最佳特定實踐)?

您可能不想將敏感數據存儲在共享首選項中。 相反,您可能想研究這樣的插件: 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);

正如我在已刪除的帖子中提到的,我一直在使用 hive 來存儲我的令牌和其他本地數據。 使用hive可以創建一個加密的盒子

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'));
}

如評論中所述:

上面的示例將加密密鑰存儲在未加密的框中。 你永遠不應該那樣做。

重要的:

  • 只有值被加密,而密鑰以明文形式存儲。
  • 確保在您的應用程序關閉時安全地存儲加密密鑰。 使用 Flutter,您可以使用flutter_secure_storage或類似的包。
  • 沒有檢查加密密鑰是否正確。 如果不是,則可能會出現意外行為。

因此,如果您不需要任何hive特定功能, flutter_secure_storage應該是您更好的選擇。

我使用https://pub.dev/packages/flutter_secure_storage將 JWT 令牌保存在本地存儲中。

import 'package:flutter_secure_storage/flutter_secure_storage.dart';

final storage = const FlutterSecureStorage();

// to save token in local storage
await storage.write(key: 'token', value: data.token);

// to get token from local storage
var value = await storage.read(key: 'token');

其他提示:

  • 不要忘記重新構建您的應用程序(有時您需要執行flutter cleanflutter pub get
  • 如果你在 iOS 中運行它,請確保 cocoapods 安裝正確。
  • 安裝 cocoapods sudo gem install cocoapods
  • 用於更新 cocoapods sudo gem install cocoapods
  • 就我而言,我需要在安裝 cocoapods 后關閉並重新打開 vscode。

使用https://pub.dartlang.org/packages/shared_preferences最適合您,因為它“為簡單數據提供了持久存儲”。

示例代碼:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM