繁体   English   中英

使用 OpenId AppAuth-Android 库时,带有隐式意图的 PendingIntent 返回取消的异常

[英]PendingIntent with implicit intent returning cancelled exception when using OpenId AppAuth-Android library

我正在尝试实现 oauth2 以使用户能够使用 Reddit 登录。 我已经使用适当的重定向 uri 在 reddit 上创建了我的应用程序。

我做了什么:一个带有登录按钮的 MainActivity。 单击登录按钮,启动授权流程。 要创建授权请求,我们需要传递一个挂起的意图,库使用它来调用我们希望在授权成功后调用的适当组件。

问题:当挂起的意图是使用隐式意图(在创建意图时仅设置操作字符串)时,库在调用挂起的意图时会收到取消的异常。 我还提到了清单文件中 MainActivity 的意图过滤器中的操作字符串。

我尝试过的: 1. 我尝试使用显式意图(定义我想在创建意图时打开的活动类)创建挂起的意图,我的活动的 onStart 被正确的意图调用。 2. 我尝试通过从活动本身直接调用挂起的意图(带有隐式意图)并成功调用它。

观察: 1. 如果我使用旧版本的库 (v0.2.0),带有隐式意图的待定意图工作正常。

当前版本的 OpenId AppAuth 库 - 0.7.1 在 Android 9 (Pie) 上测试 - OnePlus 3T

下面是我的 MainActivity.java

package com.prateekgrover.redditline;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.prateekgrover.redditline.services.RedditAuthService;

import net.openid.appauth.AuthState;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationRequest;
import net.openid.appauth.AuthorizationResponse;
import net.openid.appauth.AuthorizationService;
import net.openid.appauth.AuthorizationServiceConfiguration;
import net.openid.appauth.TokenRequest;
import net.openid.appauth.TokenResponse;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private String USED_INTENT = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button loginButton = findViewById(R.id.reddit_login);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent =  new Intent(MainActivity.this, RedditAuthService.class);
//                startService(intent);
                performRedditAuthAction(MainActivity.this, "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE");
            }
        });
    }

    public void performRedditAuthAction(Context context, String actionRedirect) {
        String uuid = UUID.randomUUID().toString();
        AuthorizationServiceConfiguration serviceConfiguration = new AuthorizationServiceConfiguration(
                Uri.parse("https://www.reddit.com/api/v1/authorize") /* auth endpoint */,
                Uri.parse("https://www.reddit.com/api/v1/access_token") /* token endpoint */
        );
        String clientId = "<my client id>";
        Uri redirectUri = Uri.parse("com.prateekgrover.redditline://oauth2callback");
        AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder(
                serviceConfiguration,
                clientId,
                "code",
                redirectUri
        );
        builder.setState(uuid);
        builder.setScopes("identity", "mysubreddits", "read", "save", "submit", "subscribe", "vote");
        AuthorizationRequest request = builder.build();
        AuthorizationService authorizationService = new AuthorizationService(context);

        String action = actionRedirect;
        Intent postAuthorizationIntent = new Intent("com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, request.hashCode(), postAuthorizationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        authorizationService.performAuthorizationRequest(request, pendingIntent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null && intent.getAction() != null) {
            String action = intent.getAction();
            switch (action) {
                case "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE":
                    redirectIntent(intent);
                    break;
                default:
            }
        }
    }

    private void redirectIntent(@Nullable Intent intent) {
        if (!intent.hasExtra(USED_INTENT)) {
            handleAuthorizationResponse(intent);
            intent.putExtra(USED_INTENT, true);
        }
    }

    private void handleAuthorizationResponse(Intent intent) {
        AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
        AuthorizationException error = AuthorizationException.fromIntent(intent);
        final AuthState authState = new AuthState(response, error);

        if (response != null) {
            AuthorizationService service = new AuthorizationService(this);
            service.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
                @Override
                public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException exception) {
                    if (exception != null) {
                    } else {
                        if (tokenResponse != null) {
                            authState.update(tokenResponse, exception);
                            System.out.println(tokenResponse.accessToken + " refresh_token " + tokenResponse.refreshToken);
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = getIntent();
        if (intent != null && intent.getAction() != null) {
            String action = intent.getAction();
            switch (action) {
                case "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE":
                    redirectIntent(intent);
                    break;
                default:
            }
        }
    }
}

清单文件:

<activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

库的相关部分 - mCompleteIntent 是我发送到库的 PendingIntent

private void extractState(Bundle state) {
        if (state == null) {
            Logger.warn("No stored state - unable to handle response");
            finish();
            return;
        }

        mAuthIntent = state.getParcelable(KEY_AUTH_INTENT);
        mAuthorizationStarted = state.getBoolean(KEY_AUTHORIZATION_STARTED, false);
        try {
            String authRequestJson = state.getString(KEY_AUTH_REQUEST, null);
            mAuthRequest = authRequestJson != null
                    ? AuthorizationRequest.jsonDeserialize(authRequestJson)
                    : null;
        } catch (JSONException ex) {
            throw new IllegalStateException("Unable to deserialize authorization request", ex);
        }
        mCompleteIntent = state.getParcelable(KEY_COMPLETE_INTENT);
        mCancelIntent = state.getParcelable(KEY_CANCEL_INTENT);
    }
private void handleAuthorizationComplete() {
        Uri responseUri = getIntent().getData();
        Intent responseData = extractResponseData(responseUri);
        if (responseData == null) {
            Logger.error("Failed to extract OAuth2 response from redirect");
            return;
        }
        responseData.setData(responseUri);

        if (mCompleteIntent != null) {
            Logger.debug("Authorization complete - invoking completion intent");
            try {
                mCompleteIntent.send(this, 0, responseData);
            } catch (CanceledException ex) {
                Logger.error("Failed to send completion intent", ex);
            }
        } else {
            setResult(RESULT_OK, responseData);
        }
    }

以防其他人偶然发现这个问题。

使用 app-auth android github 项目中的示例应用程序。 不要使用 Google CodeLabs app-auth 示例! 上面问题中的代码来自 Google CodeLabs,它很旧并且不再有效(状态为 2020 年 7 月)。 我犯了同样的错误,app-auth 在他们自己的页面/自述文件上链接了 codelab,所以我开始使用 codelabs 代码,但最终遇到了很多问题和错误。

新的 app-auth 版本 0.7.x 使用 json 配置文件,示例应用程序展示了如何处理挂起意图等周围的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM