How can I get authorization token from browser int

2020-03-30 04:56发布

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条回答
干净又极端
2楼-- · 2020-03-30 05:19

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];
}
查看更多
登录 后发表回答