Warm tip: This article is reproduced from serverfault.com, please click

Saving user credentials

发布于 2020-12-02 19:11:51

I'm creating an application that retrieves data using an API that requires email and password authentication.

I'm currently saving the data as plain text to SharedPreferences.

  1. It does not seem to me to be a completely safe and high-quality solution
  2. When I searched the internet and here on StackOverflow, everyone gives SharedPreferences as a solution

Can I ask for your opinion, or ask what do you suggest? How to create a quality login system?

Additional information:

The user has the choice of staying logged in the next time the application is turned on. If he chooses not, I still have to keep the user credentials until the application closes (due to API queries while the application is running).

(Android application in Java)

Thank you in advance for your ideas and opinions.

Questioner
Karel Krýda
Viewed
0
Son Truong 2020-12-03 16:33:02

Problem

Storing the plain username/password in mobile apps is not recommended, because it's not secure.

Solution

Using Token-Based Authentication, its workflow like this:

  • Client sends username/password to the server

  • Server check the username/password is valid, then generate a token and send the token to the client

  • Client saves this token to local storage, such as File, SharePreference, Database etc.. and use this token to call APIs from now on

Benefit

  • Don't need to store the plain username/password

  • You can store the plain username if users log out and exit the app. Next time they open the app, we could display the username on the Login screen (better user experience), they just need to enter their password.

Token usually has time expired, it means how long does it live. When a token is expired, you have 2 solutions:

  • Log out of the app and display the Login screen, users need to enter their password to get a new token

  • Using refresh token to get a new token

Back to your concern

The user has the choice of staying logged in the next time the application is turned on. If he chooses not, I still have to keep the user credentials until the application closes (due to API queries while the application is running).

  • When users choose "Do not stay next login" option, you should save it into local storage

  • Each time users open the app, if this option is true, then clear token, display the Login screen.

  • If this option is false and the token is not expired, go to the Home screen, otherwise get a new token.

Update

If you cannot change the authentication mechanism of the system, then you should you one of following options:

See more information here.