Reference version

This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo SecureStore iconExpo SecureStore

一个用于在设备本地加密并安全存储键值对的库。

Android
iOS
tvOS
Included in Expo Go
Recommended version:
~58.0.0

expo-secure-store 提供了一种在设备本地加密并安全存储键值对的方法。每个 Expo 项目都有独立的存储系统,无法访问其他 Expo 项目的存储。

底层平台可能会拒绝较大的数据载荷。过去,某些 iOS 版本会拒绝大于约 2048 字节的值。Expo 不会强制限制大小,因此,如果你计划存储非常长的字符串,请务必处理原生错误。

由于缺少 NSFaceIDUsageDescription 键,如果设备支持生物识别认证,Expo Go 中不支持 requireAuthentication 选项。

安装

Terminal
- npx expo install expo-secure-store
- yarn expo install expo-secure-store
- pnpm expo install expo-secure-store
- bun expo install expo-secure-store

If you are installing this in an existing React Native app, make sure to install expo in your project.

在应用配置中配置

如果项目使用配置插件(持续原生生成(CNG)),可以使用内置的配置插件来配置 expo-secure-store。该插件允许你配置各种无法在运行时设置、且必须通过构建新的应用二进制文件才能生效的属性。如果应用不使用 CNG,则需要手动配置该库。

Example app.json with config plugin

app.json
{ "expo": { "plugins": [ [ "expo-secure-store", { "configureAndroidBackup": true, "faceIDPermission": "Allow $(PRODUCT_NAME) to access your Face ID biometric data." } ] ] } }

Configurable properties

NameDefaultDescription
configureAndroidBackuptrue
Only for: 
Android

A boolean indicating whether to configure automatic Android backup to work correctly with expo-secure-store. Learn more.

faceIDPermission"Allow $(PRODUCT_NAME) to access your Face ID biometric data."
Only for: 
iOS

A string to set the NSFaceIDUsageDescription permission message.

Are you using this library in an existing React Native app?

将 NSFaceIDUsageDescription 键添加到 Info.plist:

Info.plist
<key>NSFaceIDUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your Face ID biometric data.</string>

平台上的值存储

Android

在 Android 上,值存储在 SharedPreferences 中,并使用 Android 的 Keystore 系统加密。

iOS

在 iOS 上,值使用 钥匙串服务以 kSecClassGenericPassword 的形式存储。**由于 iOS 钥匙串的底层特性,使用 expo-secure-store 存储的数据在卸载应用后,如果使用相同的 bundle ID 重新安装应用,仍会保留。**这是 iOS 钥匙串系统的预期行为,设计应用数据处理方式时应将其考虑在内。iOS 还提供了额外选项,可设置值的 kSecAttrAccessible 属性,用于控制何时可以获取该值。

数据持久性

expo-secure-store 旨在提供一种能够跨应用重启和更新持久保存数据的解决方案。但是,切勿将其作为不可替代的关键数据的唯一真实来源。

  • 在 Android 上:使用 expo-secure-store 保存的数据不会在应用卸载后保留。
  • 在 iOS 上:如果使用相同的 bundle ID 重新安装应用,使用 expo-secure-store 保存的数据会在应用卸载后保留。这是由 iOS 钥匙串管理已存储凭据的方式决定的。请注意,这并非有保证的行为,切勿依赖这一实现细节。

此外,如果用户的生物识别设置发生变化(例如添加了新的指纹),任何使用 requireAuthentication 选项并将其设为 true 保护的数据都将无法访问。

豁免加密提示

Apple App Store Connect 会提示你选择应用所实现的加密算法类型。这称为出口合规信息。发布应用或提交到 TestFlight 时,系统会询问此项。

使用 expo-secure-store 时,可以在应用配置中将 ios.config.usesNonExemptEncryption 属性设为 false:

app.json
{ "expo": { "ios": { "config": { "usesNonExemptEncryption": false } %%placeholder-start%%... %%placeholder-end%% } } }

设置此属性会自动处理合规信息提示。

Android 自动备份

Android 应用自动备份会自动备份面向 Android 6.0(API 级别 23)或更高版本并在其上运行的应用中的用户数据。

必须将自动备份系统配置为排除 expo-secure-store 的共享首选项条目,因为还原备份后无法解密这些条目——应用卸载时,应用的条目会从 Android Key Store 中删除。

如果应用没有任何自定义备份配置,expo-secure-store 会自动配置自动备份系统,使其忽略 expo-secure-store 数据。

如果使用自己的自动备份配置,则应在 sharedpref 域下排除 SecureStore,并在配置插件配置中将 configureAndroidBackup 设置为 false。

<!-- Android 12 及更高版本的自动备份配置 --> <data-extraction-rules> <cloud-backup> <include domain="sharedpref" path="."/> <exclude domain="sharedpref" path="SecureStore"/> </cloud-backup> <device-transfer> <include domain="sharedpref" path="."/> <exclude domain="sharedpref" path="SecureStore"/> </device-transfer> </data-extraction-rules>
<!-- Android 11 及更低版本的自动备份配置 --> <full-backup-content> <include domain="sharedpref" path="."/> <exclude domain="sharedpref" path="SecureStore"/> </full-backup-content>

用法

SecureStore
import { useState } from 'react'; import { Text, View, StyleSheet, TextInput, Button } from 'react-native'; import * as SecureStore from 'expo-secure-store'; async function save(key, value) { await SecureStore.setItemAsync(key, value); } async function getValueFor(key) { let result = await SecureStore.getItemAsync(key); if (result) { alert("🔐 Here's your value 🔐 \n" + result); } else { alert('No values stored under that key.'); } } export default function App() { const [key, onChangeKey] = useState('Your key here'); const [value, onChangeValue] = useState('Your value here'); return ( <View style={styles.container}> <Text style={styles.paragraph}>Save an item, and grab it later!</Text> {%%placeholder-start%%Add some TextInput components... %%placeholder-end%%} <TextInput style={styles.textInput} clearTextOnFocus onChangeText={text => onChangeKey(text)} value={key} /> <TextInput style={styles.textInput} clearTextOnFocus onChangeText={text => onChangeValue(text)} value={value} /> {} <Button title="Save this key/value pair" onPress={() => { save(key, value); onChangeKey('Your key here'); onChangeValue('Your value here'); }} /> <Text style={styles.paragraph}>🔐 Enter your key 🔐</Text> <TextInput style={styles.textInput} onSubmitEditing={event => { getValueFor(event.nativeEvent.text); }} placeholder="Enter the key for the value you want to get" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: 10, backgroundColor: '#ecf0f1', padding: 8, }, paragraph: { marginTop: 34, margin: 24, fontSize: 18, fontWeight: 'bold', textAlign: 'center', }, textInput: { height: 35, borderColor: 'gray', borderWidth: 0.5, padding: 4, }, });

API

import * as SecureStore from 'expo-secure-store';

Constants

SecureStore.AFTER_FIRST_UNLOCK

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. This may be useful if you need to access the item when the phone is locked.

SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

Similar to AFTER_FIRST_UNLOCK, except the entry is not migrated to a new device when restoring from a backup.

SecureStore.ALWAYS

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

The data in the keychain item can always be accessed regardless of whether the device is locked. This is the least secure option.

SecureStore.ALWAYS_THIS_DEVICE_ONLY

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

Similar to ALWAYS, except the entry is not migrated to a new device when restoring from a backup.

SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

Similar to WHEN_UNLOCKED_THIS_DEVICE_ONLY, except the user must have set a passcode in order to store an entry. If the user removes their passcode, the entry will be deleted.

SecureStore.WHEN_UNLOCKED

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

The data in the keychain item can be accessed only while the device is unlocked by the user.

SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY

Android
iOS
tvOS

Type: KeychainAccessibilityConstant

Similar to WHEN_UNLOCKED, except the entry is not migrated to a new device when restoring from a backup.

Methods

SecureStore.canUseBiometricAuthentication()

Android
iOS

Checks if the value can be saved with requireAuthentication option enabled.

Returns:
boolean

true if the device supports biometric authentication and the enrolled method is sufficiently secure. Otherwise, returns false. Always returns false on tvOS.

SecureStore.deleteItemAsync(key, options)

Android
iOS
tvOS
ParameterTypeDescription
keystring

The key that was used to store the associated value.

options(optional)SecureStoreOptions

An SecureStoreOptions object.

Default:{}

Delete the value associated with the provided key.

Returns:
Promise<void>

A promise that rejects if the value can't be deleted.

SecureStore.getItem(key, options)

Android
iOS
tvOS
ParameterTypeDescription
keystring

The key that was used to store the associated value.

options(optional)SecureStoreOptions

An SecureStoreOptions object.

Default:{}

Synchronously reads the stored value associated with the provided key.

Returns:
string | null

Previously stored value. It resolves with null if there is no entry for the given key or if the key has been invalidated.

SecureStore.getItemAsync(key, options)

Android
iOS
tvOS
ParameterTypeDescription
keystring

The key that was used to store the associated value.

options(optional)SecureStoreOptions

An SecureStoreOptions object.

Default:{}

Reads the stored value associated with the provided key.

Returns:
Promise<string | null>

A promise that resolves to the previously stored value. It resolves with null if there is no entry for the given key or if the key has been invalidated. It rejects if an error occurs while retrieving the value.

SecureStore.isAvailableAsync()

Android
iOS
tvOS

Returns whether the SecureStore API is enabled on the current device. This does not check the app permissions.

Returns:
Promise<boolean>

Promise which fulfils with a boolean, indicating whether the SecureStore API is available on the current device. Currently, this resolves true on Android and iOS only.

SecureStore.setItem(key, value, options)

Android
iOS
tvOS
ParameterTypeDescription
keystring

The key to associate with the stored value. Keys may contain alphanumeric characters, ., -, and _.

valuestring

The value to store.

options(optional)SecureStoreOptions

An SecureStoreOptions object.

Default:{}

Stores a key–value pair synchronously.

Returns:
void

SecureStore.setItemAsync(key, value, options)

Android
iOS
tvOS
ParameterTypeDescription
keystring

The key to associate with the stored value. Keys may contain alphanumeric characters, ., -, and _.

valuestring

The value to store.

options(optional)SecureStoreOptions

An SecureStoreOptions object.

Default:{}

Stores a key–value pair.

Returns:
Promise<void>

A promise that rejects if value cannot be stored on the device.

Types

KeychainAccessibilityConstant

Android
iOS
tvOS

Type: number

SecureStoreOptions

Android
iOS
tvOS
PropertyTypeDescription
accessGroup(optional)string
Only for: 
iOS

Specifies the access group the stored entry belongs to.

authenticationPrompt(optional)string

Custom message displayed to the user while requireAuthentication option is turned on.

keychainAccessible(optional)KeychainAccessibilityConstant
Only for: 
iOS

Specifies when the stored entry is accessible, using iOS's kSecAttrAccessible property. When an existing entry is overwritten, passing this option updates the entry's accessibility, and omitting it keeps the accessibility the entry was stored with.

Default:SecureStore.WHEN_UNLOCKED
keychainService(optional)string
  • Android: Equivalent of the public/private key pair Alias.
  • iOS: The item's service, equivalent to kSecAttrService.
requireAuthentication(optional)boolean

Option responsible for enabling the usage of the user authentication methods available on the device while accessing data stored in SecureStore.

  • Android: Equivalent to setUserAuthenticationRequired(true) (requires API 23).
  • iOS: Equivalent to biometryCurrentSet. Complete functionality is unlocked only with a freshly generated key - this would not work in tandem with the keychainService value used for the others non-authenticated operations.

This option works slightly differently across platforms: On Android, user authentication is required for all operations. On iOS, the user is prompted to authenticate only when reading or updating an existing value (not when creating a new one).

Warning: This option is not supported in Expo Go when biometric authentication is available due to a missing NSFaceIDUsageDescription. In release builds or when using continuous native generation, make sure to use the expo-secure-store config plugin.

requireConfirmation(optional)boolean
Only for: 
Android

Sets a hint to the system for whether to require user confirmation after authentication. This may be ignored by the system if the user has disabled implicit authentication in Settings or if it does not apply to a particular biometric modality. Defaults to true.

This option is only used when requireAuthentication is enabled.