How to securely store access token and secret in Android?

android store token in keystore
android store session token
access token android
token based authentication android
google sign in access token android
how to generate token in android
android keystore best practices
secure store android

I am going to use oAuth to fetch mails and contacts from google. I don't want to ask the user each time to log in to obtain an access token and secret. From what I understood, I need to store them with my application either in a database or SharedPreferences. But I am a bit worried about security aspects with that. I read that you can encrypt and decrypt the tokens but it is easy for an attacker to just decompile your apk and classes and get the encryption key. What's the best method to securely store these tokens in Android?

How to securely store access token and secret in Android?, I don't want to ask the user each time to log in to obtain an access token and secret. From what I understood, I need to store them with my application either in a  Let’s going to use now the NDK, and keep iterating our security mechanism. NDK allows us to access a C++ code base from our Android code. As a first approach, let’s take a minute to think what to do. We could have a native C++ function that stores an API Key or whatever sensitive data we are trying to store.

security, How do we know the petition comes from one of our verified clients, and not a random dude trying to gain access to our API? The backend will  Open "keystore.properties" file and save your Access Token and Secret in the file. Now load the read the Access Token and Secret in your app module's build.gradle file. Then you need to define the BuildConfig variable for your Access Token and Secret so that you can you can directly access them from your code.

SharedPreferences is not a secure location itself. On a rooted device we easily can read and modify all applications' SharedPrefereces xml's. So tokens should expire relatively frequent. But even if a token expires every hour, newer tokens can still be stolen from SharedPreferences. Android KeyStore should be used for long term storage and retrieval of cryptographic keys which will be used to encrypt our tokens in order to store them in e.g. SharedPreferences or a database. The keys are not stored within an application's process, so they are harder to be compromised.

So more relevant than a place is how they can be itself secure e.g. using cryptographically signed short-living JWTs, encrypting them using Android KeyStore and sending them with a secure protocol

A follow-up on how to store tokens securely in Android, Can this be achieved with Keystore? I don't think that fits your use case. Keystore is designed to store cryptographic keys that will be used for  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.

  1. From your Android Studio's Project pane, select "Project Files" and create a new file named "keystore.properties" in your project's root directory.

  1. Open "keystore.properties" file and save your Access Token and Secret in the file.

  1. Now load the read the Access Token and Secret in your app module's build.gradle file. Then you need to define the BuildConfig variable for your Access Token and Secret so that you can you can directly access them from your code. Your build.gradle may look like following:

    ... ... ... 
    
    android {
        compileSdkVersion 26
    
        // Load values from keystore.properties file
        def keystorePropertiesFile = rootProject.file("keystore.properties")
        def keystoreProperties = new Properties()
        keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    
        defaultConfig {
            applicationId "com.yourdomain.appname"
            minSdkVersion 16
            targetSdkVersion 26
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    
            // Create BuildConfig variables
            buildConfigField "String", "ACCESS_TOKEN", keystoreProperties["ACCESS_TOKEN"]
            buildConfigField "String", "SECRET", keystoreProperties["SECRET"]
        }
    }
    
  2. You can use your Access Token and Secret in your code like this:

    String accessToken = BuildConfig.ACCESS_TOKEN;
    String secret = BuildConfig.SECRET;
    

This way you don't need store the Access Token and Secret in plain text inside your project. So even if someone decompiles your APK, they will never get your Access Token and Secret as you are loading them from a external file.

How to securely store accesstoken in android, In order to securely access an online service, users need to OAuth2 provides a single value, called an auth token, that represents both the A client id and client secret, which are strings that identify your app to the service. and they need to log in again, or perhaps their stored credentials are incorrect. Protecting the secret at rest. As a first step, using something like proguard will help to make it less obvious where any secrets are held. You could also use the NDK to store the key and secret and send requests directly, which would greatly reduce the number of people with the appropriate skills to extract the information.

Well you can secure you access token by following two options.

  1. Use save your access token into android keystore that would not be reverse.
  2. Use NDK function with some calculation that save your token and NDK with c++ code that is very hard to reverse

Authenticate to OAuth2 services, Store tokens in a secure storage that the OS offers and limit access to that storage. For example, leverage KeyStore for Android and KeyChain for iOS. Use the  Obtaining Tokens an API Keys. When it comes to using an API, you are usually offered two choices: pass a static piece of information together with the API call or obtain that piece of information dynamically prior to invoking the API. This piece of information is usually an access token or API key.

Token Storage, I've been developing android apps for over 3 years now and I'm also a security enthusiast. So please add a key to your API and bonus point add a user token in key store in Java/Kotlin code because they are pretty easy to access Last thing here never ever put a server secret key in the client code. Because the client needs to use the token, it will have to be decrypted somewhere, hence the decryption key is on the mobile device as well. Encrypting the token doesn't make it secure, it would only delay an attacker. That is why tokens are normally short lived and have limited permissions as compared to what a username and password can manage.

Developing Secure Android Apps., This article focuses on security best practices for access token running on the server side and capable of safely storing an application secret. How and where to securely store tokens used in token-based authentication depends on the type of app you are using. ID Tokens, Access Tokens, and (optional) Refresh Tokens should be handled server-side in typical web applications. The application server use the tokens to call APIs on behalf of the user. Securing single page apps (SPAs) comes

Security Best Practices for Managing API Access Tokens, The simplest approach for storing secrets in to keep them as resource files Now you have access to as many secret values as you need within your app, https://medium.com/@ericfu/securely-storing-secrets-in-an-android-  KeyChain is used to store values securely on iOS devices. The SecRecord used to store the value has a Service value set to [YOUR-APP-BUNDLE-ID].xamarinessentials . In some cases KeyChain data is synchronized with iCloud, and uninstalling the application may not remove the secure values from iCloud and other devices of the user.

Comments
  • How do i store the consumer key and secret (hardconding them is not secured)? i need them to request the accesstoken and secret.. how do the other existing apps using oauth do it? hmm finally with oauth, you need to take care of much more security issues for me.... i need to keep the consumer token/secret securely and also the accesstoken and secret.... finally wouldn't it be more simple to just store the user's username/password encrypted?... in the end, isn't the latter better? I just still can't see how oauth is better...
  • can you tell me..which file stores the access token ?? I am new to android and i tried running sample Plus app.But i dont find this anywhere [GoogleAuthUtil.getToken() method.]
  • thx for the reply! but how can i know if my consumer key has been compromised? lol it's will be hard to tell.. ok about storing the access token and secret, ok i save them in sharedpreferences and encrypting them but how about consumer key and secret? I can't store them in sharedpreferences (I would need to explicitly write the consumer key and secret in the code to save it in sharedpreference in the first place).. don't know if you understand what i mean.
  • You have to either put the in the app in a (somewhat) obfuscated way, to they are not immediately visible after decompilation, or use your own authrorization proxy webapp that has the key and secret. Putting them in the app is obviously easier, and if think the risk of someone trying to crack your app is sufficiently low, take that approach. BTW, the points above are for the user password. If you find out your consumer key/secret have been compromised, you can revoke those too (that will, of course, break your app though).
  • @NikolayElenkov: You wrote 'As for encryption, you have to either require the user to enter the decrypt passphrase every time (thus defeating the purpose of caching credentials), or save the key to a file, and you get the same problem.'. What if crackers reverse your app to get insight how the encryption works? Your defense may be broken. Is it a best practice to store such information (token, encryption...) using native code?
  • If app data is cleared, then the refresh token is lost, which is probably not what the user wanted.
  • This is not the best way to store tokens anymore now-a-days!
  • Good tip that Conceal. Looks very easy to use. And for many use cases.
  • Then where we can store them?
  • Looks like there is no difference that creation a properties file instead hard coding.
  • I want to write Token on run time might be my token is every time changed when i open my app.
  • It's a very good way to store some tokens like API access tokens. if you want to store user credentials the NDK is a better way.
  • This is absolutely not how you should go about storing sensitive information in your application! Even if the repository doesn't contain the data by using this approach (the data is injected into the build process) this generates a BuildConfig file that has the token/secret in plain text for all to see after a simple decompile.