Search code examples
androidoauthaccess-tokenandroid-security

How to save Oauth Access token securely in android


I have access token from the server after authentication lets say "uyhjjfjfgg567f8fhjkkf" now I want to save it in the device securely. I looked in Keystore and Keychain in android developer sites. I dont clearly understand how it works and how we should retrieve the token from the keystore.

KeyPairGenerator kpg = KeyPairGenerator.getInstance(
        KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
kpg.initialize(new KeyGenParameterSpec.Builder(
        alias,
        KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
        .setDigests(KeyProperties.DIGEST_SHA256,
            KeyProperties.DIGEST_SHA512)
        .build());

KeyPair kp = kpg.generateKeyPair();


/*
 * Load the Android KeyStore instance using the the
 * "AndroidKeyStore" provider to list out what entries are
 * currently stored.
 */

KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
Enumeration<String> aliases = ks.aliases();

Solution

  • You don't need to save the access token, since it has short life anyway. Keeping it in memory is good enough.

    You do need to keep the refresh token, and you have a few options for that:

    • In a file
      • Either directly in a file in the internal storage
      • or using SharedPreferences
      • or in a Database
    • Using the AccountManager

    Consider using the StoredCredential. For the flow itself, I recommend you to use Google AppAuth library.

    Of course, you can also encrypt the key using a cipher:

    private static byte[] encrypt(byte[] key, byte[] text) throws GeneralSecurityException {
        final SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
        final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, sInitVectorSpec);
        return cipher.doFinal(text);
    }
    

    And the key can be stored in the KeyStore.