2012-04-14 139 views
1

我想創建和Android應用程序,需要用戶進行身份驗證(通過REST Web服務)。該應用程序有多個活動和屏幕,都需要用戶登錄,登錄時用戶可以在網站上添加和編輯帖子。Android身份驗證

我讀過在「ConnectionManager」單身人士中使用AndroidHttp客戶端是最好的方法。然而,我會在哪裏存儲用戶的詳細信息(用戶名,密碼),這將在單身?每次用戶嘗試編輯/添加內容時,我是否應該進行身份驗證?

我應該有一個這樣的類:

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 
    } 
} 

,並調用下面的代碼每個用戶做了一次:

private static ConnectionManager conn = ConnectionManager.getInstance(); 
conn.authenticate(); 

OR

我應該存儲用戶單身的細節

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; 
    } 
} 

回答

2

如果您擁有Rest服務的控制權,則可以在初始連接上使用用戶名\密碼進行身份驗證,然後在身份驗證成功時將「令牌」返回給您的應用程序。

然後,您的應用程序可以將此令牌添加到所有未來請求的http標頭中,並且您的服務可以在繼續之前檢查它是否有效。

這就是我的做法,它運作良好。

+0

這似乎是有道理的,這種方法是否安全?你知道如何實現這個目標的例子嗎? – kiwijus 2012-04-14 15:26:51

+0

您需要使用SSL才能保證安全,但對於任何服務都是如此。我不知道任何記錄的例子,但它並不困難。 – Kuffs 2012-04-14 15:47:29

+0

是的,我認爲它可能會很好。我剛看了一下,看起來很簡單。這只是在Android應用程序(HttpGet addheader)中添加標題然後在Web服務端檢查它的問題?我不會錯過任何我? – kiwijus 2012-04-14 15:50:02