使用OpenId AppAuthAndroid库时,具有隐式意图的java PendingEvent返回已取消的异常
我正在尝试实现oauth2,以允许用户使用Reddit登录。我已经在reddit上用适当的重定向uri创建了我的应用程序
我所做的: 带有登录按钮的MainActivity。单击登录按钮,启动授权流。要创建授权请求,我们需要传递一个挂起的意图,库使用该意图调用我们希望它在授权成功后调用的适当组件
问题: 当使用隐式意图创建挂起的意图(在创建意图时仅设置操作字符串)时,库在调用挂起的意图时会收到一个已取消的异常。我还提到了清单文件中MainActivity的意图过滤器中的操作字符串
我尝试过的: 1.我尝试使用显式意图创建挂起的意图(定义创建意图时我要打开的活动类),我的活动的onStart被正确的意图调用。 2.我尝试直接从活动本身调用挂起的意图(带有隐式意图),结果成功地调用了它
观察: 1.如果我使用较旧版本的库(v0.2.0),带有隐式意图的挂起意图可以正常工作
OpenId AppAuth库的当前版本-0.7.1 在Android 9(Pie)上测试-OnePlus 3T
下面是我的主要活动。爪哇
package com.prateekgrover.redditline;
import 安卓x.annotation.Nullable;
import 安卓x.appcompat.app.AppCompatActivity;
import 安卓.app.PendingIntent;
import 安卓.content.Context;
import 安卓.content.Intent;
import 安卓.net.Uri;
import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.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 安卓:name=".MainActivity" >
<intent-filter>
<action 安卓:name="安卓.intent.action.MAIN" />
<category 安卓:name="安卓.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action 安卓:name="com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE"/>
<category 安卓:name="安卓.intent.category.DEFAULT"/>
</intent-filter>
</activity>
图书馆的相关部分-MCOMPLETETINTENT是我发送给图书馆的悬而未决的内容
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);
}
}
# 1 楼答案
以防其他人偶然发现这个问题
使用app auth android github项目中的示例应用。 不要使用Google CodeLabs应用程序验证示例!上面问题中的代码来自Google CodeLabs,它非常古老,不再有效(2020年7月发布)。 我也犯了同样的错误,app auth在他们自己的页面/自述中链接了codelabs,所以我开始使用codelabs代码,结果出现了很多问题和错误
新的应用程序auth版本为0.7。x使用一个json配置文件,示例应用程序展示了如何处理未决意图等方面的错误