Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use `SharedPreferences` to store authentication token

Tags:

android

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.

like image 855
Max Koretskyi Avatar asked May 27 '15 14:05

Max Koretskyi


People also ask

Where should authentication tokens be stored?

# 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.

Is it safe to store token in SharedPreferences?

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.

Where should bearer tokens be stored?

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.

What can be stored in SharedPreferences?

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.


2 Answers

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.

like image 114
Bidhan Avatar answered Oct 26 '22 23:10

Bidhan


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

like image 20
Blackbelt Avatar answered Oct 27 '22 01:10

Blackbelt