How can I get authorization token from browser intent?

Deadly 提交于 2019-12-01 11:15:26

问题


Sorry for my bad English, I'll try to explain my problem as simple as I can. I'm trying to make an app, which works with Yandex API. On their help page, I've read that you should launch browser from app where user logins and then return to application by registering URI Callback. What I have now:

 @Override
 public void onClick(View view) {
 Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://oauth.yandex.ru/authorize?response_type=token&client_id=XXXXXXXXXXXXXXX"));
 startActivity(browserIntent);
}

This launches browser and redirects to authorization page. After entering login-password I return automatically to my app. Here's AndroidManifest:

 <activity
            android:name="ru.mastergroosha.yaruclient.Main"
            android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
            android:name="ru.mastergroosha.yaruclient.Window"
            android:label="Window">
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data
                    android:scheme="yaruapp"
                    android:host="token"/>
        </intent-filter>
    </activity>

And when I entered login-password I'm redirected to page like "yaruapp://token#access_token=YYYYYYYYYYYYYYY&token_type=code..." and so on. But I don't see this page because redirected instantly back to app.

The question is: how can I get and extract this part: YYYYYYYYYYYYYY ?

I'm terribly sorry for being so noobish, hope you can help me. Thanks in advance


回答1:


You can get the Uri in onNewIntent. Just override it in your Activity. You can get the access token with something like the following:

@Override
protected void onNewIntent (Intent intent){
  Uri uri = intent.getData();
  if (uri!=null){
    String mainPart = uri.toString().split("#")[1];
    String[] arguments = mainPart.split["&"];
    String argument = arguments[0];
    String token = argument.split("=")[1];
}


来源:https://stackoverflow.com/questions/17979589/how-can-i-get-authorization-token-from-browser-intent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!