I use token based authenticated mechanism on my server. When user logins through Android app the server returns token which needs to be sent with each subsequent request. I need to store that value on the devices. Since token is a simple string, I thought I'd use SharedPreferences
to hold that value. When application starts inside MyApplication extends Application
I query SharedPreferences
for this token and hold it inside MyApplication
as a global state so that every activity could access it when it sends request to the server.
Is this approach viable? If not, what critical drawbacks does it have? And if it's a bad idea, what's the alternative approach?
PS. This is not a subjective question - I'm not asking for the best
approach, I'm validating my assumptions.
# Tokens stored in localStorage are automatically protected from CSRF attacks, because localStorage items are not automatically sent to servers with each HTTP request. But they are vulnerable to XSS attacks, where they can be easily accessed by JavaScript.
If there is concern that the token could be read from SharedPreferences, a good rule of thumb is to provide a certain level of obfuscation to the data being stored. it's not encryption, it's obfuscation. if the key is stored on the device, you're just adding a level of indirection to your sensitive data.
Should you keep tokens in cookies or in local storage? There are two patterns for client-side storage of bearer tokens: cookies and using HTML5 local storage. If cookies are being used to transmit the bearer token from client to server, then cookies would also be used to store the bearer token on the client side.
There is a limit to what we can store in SharedPreferences out of the box. In other words, we can store the following data types boolean, int, long, float, string and stringSet.
It's fairly safe. The users wont have access to the SharedPreferences
unless they have rooted their devices. If you're concerned about security that much, you could encrypt the token before storing it inside SharedPreferences
.
it is a valid option, if you don't want to use a database
or write the token on a file. No drawbacks that I can think of
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With