Junior — Middle
How did you handle the token when receiving it in your last project?
sobes.tech AI
Answer from AI
In my last project, when obtaining a token, I implemented the following approach:
-
Secure storage: The token was stored in a protected storage, such as EncryptedSharedPreferences on Android or a secure key storage.
-
Token refresh: When a new token was received, the old one was replaced to always use the current token.
-
Error handling: If the token was not received or expired, logic was implemented to retry the request or transition to the login screen.
-
Using the token: The token was added to HTTP request headers for server authentication.
Example in Kotlin for Android:
// Saving the token
fun saveToken(token: String) {
val prefs = EncryptedSharedPreferences.create(
"prefs",
masterKey,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
prefs.edit().putString("auth_token", token).apply()
}
// Retrieving the token
fun getToken(): String? {
val prefs = EncryptedSharedPreferences.create(...)
return prefs.getString("auth_token", null)
}
Thus, security and relevance of the token in the application were ensured.