Android 原生app獲取使用者授權訪問Autodesk雲應用資料
oAuth機制對於網站間的授權管理是很容易實現的,設定好app回撥埠,當資料服務提供方拿到其使用者授權,則返回授權碼傳送到回撥埠。上一篇文章介紹了 如何授權Forge app訪問Autodesk 雲應用資料 ,即,獲取三條腿的token。
但移動端的原生app,授權碼返回到發起請求app的某個Activity,可如何得知是哪個Activity並且跳轉到此Activity?這時就要用到 URL Scheme 。iOS和Android都提供了這樣的機制。它實現了頁面內跳轉協議,通過定義自己的scheme協議,非常方便跳轉到app中的各個Activity。也讓不同app可以喚起其它app的Activity。當然,前提app已經安裝到系統。這位大咖對此話題做了專業的講解,推薦大家先閱讀:
https://www.jianshu.com/p/7b0...我的同事Bryan搭建了一個框架,演示Android app 整合Forge oAuth,拿到三條腿token,並呼叫了使用者資訊(Profile)API,列出登入使用者的在Forge資料管理中的基本資訊。該框架很好的展示了使用 URL Scheme 整個過程。
https://github.com/dukedhx/oa...我藉此學習了有關內容。另外,基於此程式碼,略微改造,新增流程展示獲取Autodesk雲應用的Hub,Project,Folder和File,為進一步的綜合應用app做一些鋪墊。
https://github.com/xiaodongli...
oAuth相關的幾個步驟:
1.定義監聽oAuth回傳的Activity屬性
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> <intent-filter> <data android:scheme="@string/FORGE_CALLBACK_SCHEME" android:host="@string/FORGE_CALLBACK_HOST"/> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> </intent-filter> </activity>
其中,FORGE_CALLBACK_SCHEME和FORGE_CALLBACK_HOST定義為:
<string name="FORGE_CALLBACK_SCHEME">lxdapp</string> <string name="FORGE_CALLBACK_HOST">mytest3legged</string>
同樣的, URL Scheme必須和Forge app註冊的時候填寫的callback URL要一致。
2.登入事件將建立一個Intent.ACTION_VIEW,用以啟動網頁,URL拼接了Forge app的client id,授權方式 (response_type=code),回傳地址和授權的許可權範圍 跳轉到Autodesk登入過程,等待客戶授權。
public void onLoginClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); Resources resources = getResources(); i.setData(Uri.parse(getResources().getString(R.string.FORGE_AUTHORIZATION_URL) + "?response_type=code&redirect_uri=" + this.getCallbackUrl() + "&scope=" + resources.getString(R.string.FORGE_SCOPE) + "&client_id=" + resources.getString(R.string.FORGE_CLIENT_ID))); startActivity(i); }
3.使用者授權後,將對URLScheme地址回傳,也就是發起請求的Activity。Activity的OnStart拿到回傳資訊。由於沒有設定android:mimetype, 則任何資料型別都可接收。但我們需要只是授權碼,在回傳請求的URL引數中。
@Override protected void onStart() { super.onStart(); Intent intent = getIntent(); Uri data = intent == null ? null : intent.getData(); //從回傳請求中拿到授權碼 String authorizationCode = data == null ? null : data.getQueryParameter("code"); if (authorizationCode != null && !authorizationCode.isEmpty()) { ......
4.接下來的過程就和常規的網頁應用類似了,依授權碼得到最終的token。
5.該樣例呼叫Forge服務採取 okhttp3 ,推薦參考下文的詳細講解:
https://www.jianshu.com/p/da4...注:
- Activity的URLScheme是可能同名的,而且如何保證應用之間跳轉和傳參的目標正確性,這方面我還在研究中。
- 本例為方便計,將Forge Client Secret也存在了app之中。我想安全的方式是由app伺服器端進行secret的管理,當原生app拿到授權碼,通過它來向app伺服器端發起請求,由app伺服器來獲取Forge token,再傳回原生app。
- 擴充套件的部分(Hub,Project,Folder和File)只是簡單的替換ListView的內容,尚未對頁面回退做處理。