# React Nativeでセキュアな環境にTokenを保存する

2 min read
Table of Contents

要はブラウザ委のストレージのような機能をアプリでどう再現するかを調べてみた。

iOSでは KeyChainAndroidでは KeyStoreという安全に重要情報を保存できる場所が用意されているらしい。

Expo Cliではreact-native-keychainが使えない。

で、React Nativeではreact-native-keychainというプラグインで実現できるらしいが、Expo Cliでは使えないらしい。これは落とし穴だった。結構な時間を溶かした。

expo-secure-storeを使用しよう

公式サイト

Terminal window
npx expo install expo-secure-store

でインストールする。

app.jsonに下記を追加する。

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

実装

ログインボタンを押したときにアクセストークンを保存する。

<Button
title="Log in"
onPress={async () => {
try {
// ログイン処理
// トークンを保存してメイン画面に遷移
await SecureStore.setItemAsync("accessToken", "userToken");
navigation.navigate("Main");
} catch (error) {
console.error("SecureStore error: ", error);
}
}}
/>

遷移先のページでチェックする。

async function getValueFor(key:string) {
let result = await SecureStore.getItemAsync(key);
if (result) {
console.log("🔐 Here's your value 🔐 \n" + result);
} else {
console.log('No values stored under that key.');
}
}
useEffect(() => {
(async() => {
await getValueFor('accessToken')
})()
}, []);

削除はSecureStore.deleteItemAsync(key, options)で実装できる。

My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments