Should I keep tokens safely in memory or sqlite? Or please suggest
I
started learning Android a few days ago, and so far I’ve completed the implementation of the login activity, with the main activity extending the abstract base activity.
Clicking on a navigation bar item opens the xml from Fragments.
I
have a question about the token I received after a successful login. This token is used with each request to get data after a successful login. Should I keep the token safely in the sqlite database, or should I create a public property in the main activity? The Main Activity will always remain in memory because this will open the fragment.
Solution
I can suggest 3 options:
1) You can save the token to a file as follows:
public static void saveToken(Context ctx, String fileName, Object token) {
if (token == null) {
ctx.deleteFile(fileName);
} else {
ObjectOutputStream out = null;
try {
FileOutputStream fout = ctx.openFileOutput(fileName, 0);
out = new ObjectOutputStream(fout);
out.writeObject(token);
fout.getFD().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Ensure that the object token
implements the java.io.Serializable interface.
Usage prior to API level 24:
saveToken(appContext, someFileName, someTokenObject);
API level 24 and higher usage:
saveToken(appContext.createDeviceProtectedStorageContext(), someFileName, someTokenObject);
2) Encrypt the database using the SQLCipher library.
3) You can encrypt your token using the keystore system https://developer.android.com/training/articles/keystore.html