I am trying to create and Android app that requires the user to be authenticated (through a REST web service). The app has multiple activities and screens that all require the user to be logged in, when logged in the user can add and edit posts on a website.
I have read that using a AndroidHttp Client within a "ConnectionManager" singleton would be the best way to do it. However where would I go about storing the users details (username, password), would this be in the singleton? Should I authenticate each time the user try's to edit/add something?
Should I have a class like this:
public class ConnectionManager {
private static ConnectionManager instance = null;
private AndroidHttpClient client;
private ConnectionManager() {
client = AndroidHttpClient.newInstance("Android-Connection-Manager");
}
public static ConnectionManager getInstance() {
if( instance == null ) {
instance = new ConnectionManager();
}
return instance;
}
public void authenticate(String username, String password) {
//Check for authentication here
}
}
and call the below code every time the user does something:
private static ConnectionManager conn = ConnectionManager.getInstance();
conn.authenticate();
OR
should I store the users details in the singleton
public class ConnectionManager {
private static ConnectionManager instance = null;
private AndroidHttpClient client;
private AppUser mLoggedInUser;
private boolean mAuthenticated;
private ConnectionManager() {
client = AndroidHttpClient.newInstance("Android-Connection-Manager");
}
public static ConnectionManager getInstance() {
if( instance == null ) {
instance = new ConnectionManager();
}
return instance;
}
public void InitialiseUser(String username, String password) {
//Do login checks here then return true if logged in
mAuthenticated = true;
}
public boolean isAuthenticated() {
return mAuthenticated;
}
}
If you have control of the Rest Service, you could authenticate using the username\password on the initial connection and then return a "token" to your app if authentication succeeds.
Your app could then add this token to the http headers of all future requests and your service could check that it is valid before proceeding.
That is how I did it and it works well.