1. 程式人生 > >Android使用token維持登陸狀態

Android使用token維持登陸狀態

什麼是token

token(令牌)是一串唯一的字串,通常由服務端生成,在註冊完成時返回給客戶端,用來標識此使用者,客戶端將此字串儲存在本地。在以後的網路請求時,客戶端先查詢本地的token,如果有則直接使用此令牌進行網路請求,沒有則提示未登入,轉到登陸註冊介面。
此外,還可以在服務端或者客戶端新增過期判別機制。

token的作用

token可以顯著減少服務端對使用者表的查詢,同時使使用者不必每次都登陸,提高了系統的可用性與健壯性。

使用SharedPreferences儲存token

獲取token並儲存

NetWorks.regPost(user, password, email, tel, new Observer<User>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {                
                Log.e
("LoginActivity",e.getLocalizedMessage()+"--"+e.getMessage()); } @Override public void onNext(User user) { if(user.getmMessage().equals("success")){ MainActivity.instance.finish();//結束原來的主頁面 Toast.makeText(getApplicationContext(),"註冊成功"
,Toast.LENGTH_SHORT).show(); //token儲存到本地 SharedPreferences sp = getSharedPreferences("loginToken", 0); SharedPreferences.Editor editor = sp.edit(); editor.putString("userId",user.getmUserId()); editor.putString
("userName",user.getmUserName()); editor.putString("phone",user.getmPhone()); editor.putString("email",user.getmEmail()); editor.putString("headImageUrl",user.getmHeadImageUrl()); editor.commit(); Intent i = new Intent(RegActivity.this,MainActivity.class); startActivity(i); finish(); }else{ Toast.makeText(getApplicationContext(),"註冊失敗"+user.getmMessage(),Toast.LENGTH_SHORT).show(); } } });

我使用的是retrofit框架進行網路請求,上文是實現註冊功能的函式,在onNext()函式中獲取服務端返回的結果,這個框架自動把返回的json資料解析為對應的類物件(即上文中的user物件)。因為token的本質是唯一的字串,userId滿足這個要求,因為userId是由服務端生成且唯一,故我將userId作為token使用。

進行網路請求前查詢本地token

比如點選側邊欄的頭像,如果未登入則需要跳轉到登陸介面,已經登陸則進入個人資訊介面。這時候,就需要查詢本地token進行判別。

private void initData() {
        sp = getSharedPreferences("loginToken", 0);
        name = sp.getString("userId", null);
        userName = sp.getString("userName", null);
        email = sp.getString("email", null);      
    }
@Override
    public void onClick(View view) {
        switch (view.getId()) {         
            case R.id.imageView:
                if (name == null) {
                    Intent i = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(i);
                } else {
                    Log.d("使用者ID", name);
                    Intent i = new Intent(MainActivity.this, PersonInfoActivity.class);
                    startActivity(i);
                }
                break;

        }
    }

備註

在此例中,我使用userId作為token,但並不建議這麼做,雖然這樣很簡單。因為userId顯然無法判別是否過期,如果我們需要實現token過期的判別,則可以採用將userId與日期拼接的方式。
此外,為了安全起見,不要在客戶端生成token。