且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的身份验证

更新时间:2023-12-02 09:51:04

如果您有REST服务的控制权,你可以验证初始连接上使用的用户名\\密码,然后返回一个令牌,以您的应用程序,如果认证成功。

您的应用程序可能再此令牌添加到所有未来的请求的HTTP标头和您的服务可以检查它在继续之前是有效的。

这是我做到了,效果很好。

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.