Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

動手做新浪微博 Android 客戶端:OAuth 授權篇(2.1)

編輯:Android 開發實例

      這一篇專門談 OAuth 授權認證。新浪的開放 API 全都建立在這套機制之上,不把它弄懂,後面的功能寫不動,所以值得單獨拉出來講。

     前文提過,新浪微博同時提供 OAuth 與 Base OAuth 兩種認證方式,本專案採用的是 OAuth。為什麼不用 Base OAuth?理由很實際:自從 Twitter 宣布只支援 OAuth 之後,各大服務紛紛跟進轉向,新浪微博的開放平台也預告將停止 Base OAuth 認證,早點靠攏總沒吃虧。

OAuth 到底解決了什麼問題

     OAUTH 協議為「使用者資源授權」提供了一套安全、開放又簡易的標準。它與傳統授權方式最大的差異在於:第三方永遠碰不到使用者的帳號資訊(帳號與密碼)。也就是說,第三方不需要掌握帳密,也能取得存取該使用者資源的授權,這正是 OAuth 安全性的根源。

     新浪微博採用 OAuth,同樣是為了守住帳號密碼這條底線。透過 OAuth,普通使用者、我們正在開發的這個 Android 客戶端、新浪微博三方之間建立起信任關係:客戶端不需要知道帳密,一樣能瀏覽與發布微博。既保護了帳號安全,又達到了「用客戶端看微博、寫微博」的目的——這就是 OAuth 的價值所在。

四組關鍵字

     結合新浪微博的實作來看,接下來整個流程都圍繞著四組參數打轉:

     第一組:App Key 與 App Secret。這組就是本系列第一篇提到的,到開放平台建立新應用後取得的憑證。

     第二組:Request Token 與 Request Secret。

     第三組:oauth_verifier。

     第四組:user_id、Access Token 與 Access Secret。

完整流程

   使用者第一次打開我們的客戶端時,客戶端先帶著第一組參數向新浪微博發出請求;新浪驗證通過後回傳第二組,這一步代表「新浪信任這個客戶端」。接著客戶端拿第二組當參數,引導使用者開啟瀏覽器跳到新浪微博的授權頁面,使用者在該頁面上輸入自己的微博帳密完成授權;授權成功後,新浪會依客戶端設定的回呼網址把第三組參數送回,這一步代表「使用者也信任這個客戶端」。最後客戶端把第二組與第三組一起送出,新浪回傳第四組。第四組務必妥善保存,它就是後續代替帳密調用 API 的通行證。

   回看整個過程會發現:使用者只在新浪的認證網頁裡輸入過帳密,從未在客戶端裡輸入;客戶端手上只有第四組資料,完全沒有接觸帳密。帳號密碼因此不會洩漏給新浪以外的第三方應用,安全性就是這樣被保住的。

用 oauth-signpost 簡化實作

   為了加快開發,本專案直接採用 oauth-signpost 開源專案來處理 OAuth 細節,並新建 OAuth.java 做一層輕量封裝。這個類別主要提供三個方法:RequestAccessToken 對應流程中取得第三組參數的那一步,GetAccessToken 負責換取第四組,SignRequest 則是呼叫 API 時幫請求加上簽章。有了 signpost 代勞,程式碼短了很多:

public class OAuth {
    private CommonsHttpOAuthConsumer httpOauthConsumer;
    private OAuthProvider httpOauthprovider;
    public String consumerKey;
    public String consumerSecret;

    public OAuth() {
        // 第一組:App Key 與 App Secret,請換成自己應用的憑證
        this("YOUR_APP_KEY", "YOUR_APP_SECRET");
    }

    public OAuth(String consumerKey, String consumerSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
    }

    public Boolean RequestAccessToken(Activity activity, String callBackUrl) {
        Boolean ret = false;
        try {
            httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
            httpOauthprovider = new DefaultOAuthProvider(
                "https://api.t.sina.com.cn/oauth/request_token",
                "https://api.t.sina.com.cn/oauth/access_token",
                "https://api.t.sina.com.cn/oauth/authorize");
            String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, callBackUrl);
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
            ret = true;
        } catch (Exception e) {
        }
        return ret;
    }

    public UserInfo GetAccessToken(Intent intent) {
        UserInfo user = null;
        Uri uri = intent.getData();
        String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
        try {
            httpOauthprovider.setOAuth10a(true);
            httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
        } catch (OAuthMessageSignerException ex) {
            ex.printStackTrace();
        } catch (OAuthNotAuthorizedException ex) {
            ex.printStackTrace();
        } catch (OAuthExpectationFailedException ex) {
            ex.printStackTrace();
        } catch (OAuthCommunicationException ex) {
            ex.printStackTrace();
        }
        SortedSet<String> user_id = httpOauthprovider.getResponseParameters().get("user_id");
        String userId = user_id.first();
        String userKey = httpOauthConsumer.getToken();
        String userSecret = httpOauthConsumer.getTokenSecret();
        user = new UserInfo();
        user.setUserId(userId);
        user.setToken(userKey);
        user.setTokenSecret(userSecret);
        return user;
    }

    public HttpResponse SignRequest(String token, String tokenSecret, String url, List params) {
        HttpPost post = new HttpPost(url);
        try {
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 關閉 Expect:100-Continue 握手。
        // 這個握手需謹慎使用:遇到不支援 HTTP/1.1 的伺服器或代理時容易出問題。
        post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        return SignRequest(token, tokenSecret, post);
    }

    public HttpResponse SignRequest(String token, String tokenSecret, HttpPost post) {
        httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
        httpOauthConsumer.setTokenWithSecret(token, tokenSecret);
        HttpResponse response = null;
        try {
            httpOauthConsumer.sign(post);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        }
        try {
            response = new DefaultHttpClient().execute(post);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}

 

      至此 OAuth 功能類就完成了,後續每一篇都會用到它。本篇先到這裡,敬請期待下一篇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved