I want to know what the method used by popular apps are.
Here are the approaches I have considered:
- When user logs in, save username & password in shared preferences and re-use it every time (I think this will suck)
- Login on the client(app) side with Facebook SDK, pass the authentication token to the app and use that to create a user. Pass a token to the app, store this token on the phone and use it in future communications. I think it would make sense to re-create this token periodically, but how to do so without asking the user to login again?
- Create a login view. this will mean passing username and password to the API And then go with the user token.
I don't think you should store user credentials in preferences.
The most common approach is to send credentials to server and then as a response get a session key. Then include the session key as a header to any request (and validate it in every request).
If the session key would become invalid (e. g. expired) then the server should return a proper response, and the client should initialize authentication functionality.
Egzample
First run
- Show login
Activity
- Send credentials to server
- Get a
session_key
as a response (normally its a hash) - Store the
session_key
hash - User is authenticated, exit the login
Activity
Any request to the server.
- Add a header with
session_key
to your request (e. g. as a header) - Send the request
- If the response is Ok Stop, else (e. g. response with message "not authorized" or status code 401) run
First run
First run
- Show login Activity
- Send credentials to server
- Get a session_key
- User is authenticated, exit the login Activity
- you get the access tokens and login details to stored in Shared Preferences
For other request.
- Add a header with session_key to your request (e. g. as a header)
- Send the request
来源:https://stackoverflow.com/questions/22660848/android-with-django-how-to-keep-user-logged-in