Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to store globals (auth token) in Android

I'm pretty new to android. I want to know where the best place is to store something like a auth token that I get from logging in on my server. With every subsequent request, I will have to post this auth token. Sure I could keep a global class somewhere, but I just want to know what a good / standard way is to store data that persists across activities and intents. Thanks!

like image 917
botbot Avatar asked Sep 08 '13 07:09

botbot


People also ask

Where are Android auth tokens saved?

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.

Where do you store frontend tokens?

Where should I store my tokens in the front-end? There are two common ways to store your tokens. The first is in localStorage and the second is in cookies. There is a lot of debate over which one is better with most people leaning toward cookies as they are more secure.


1 Answers

SharedPreferences is the way to go. See doc here: https://developer.android.com/reference/android/content/SharedPreferences.html

Some example code is like below.

To save the token:

SharedPreferences settings = PreferenceManager
                            .getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(some_key, your_auth_token_string);
editor.commit();

To get the token:

SharedPreferences settings = PreferenceManager
                            .getDefaultSharedPreferences(context);
String auth_token_string = settings.getString(some_key, ""/*default value*/);
like image 82
Mine Avatar answered Oct 13 '22 01:10

Mine