Eugene Reydel
Eugene Reydel

Reputation: 41

How to store jwt in android app in right way?

I have an android application where the user needs to send requests using a JSON Web Token (access/refresh tokens). Where i need to store it in right way (or best practices) in terms of both security and ease of access to it. I've heard about SharedPreferences and AccountManager, but opinions differ from source to source.

Upvotes: 4

Views: 2810

Answers (2)

Gary Archer
Gary Archer

Reputation: 29208

I have an Android Code Sample that encrypts tokens before storing in Shared Prefs, since ithis is not secure storage by default. Also it avoids asking end users token storage questions they would not understand.

You can download and run my app easily and you will notice that on restarting the app there are no login prompts:

When the app first runs it uses the Android Key Store to generate a key for the app, which only your app knows:

My solution is based on the Okta Android SDK so that is also a good place to look.

Upvotes: 1

Abhishek Dubey
Abhishek Dubey

Reputation: 945

Shared preferences would be the best option for storing tokens. This storage is app-specific and other apps cannot access this space. 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 your problem remains the same. I am attaching the details to use sharedPrefs below -

How to Initialize?

// 0 - for private mode`
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); 

Editor editor = pref.edit();

How to Store Data In Shared Preference?

editor.putString("key_name", "string value"); // Storing string

OR

editor.putInt("key_name", "int value"); //Storing integer

And don't forget to apply :

editor.apply();

How to retrieve Data From Shared Preferences ?

pref.getString("key_name", null); // getting String

pref.getInt("key_name", 0); // getting Integer

Hope this will Help U :)

Upvotes: -1

Related Questions