Вход в Android с помощью AppAuth не может перехватить ответ авторизации

Я выполнил лабораторию кода для аутентификации с помощью входа в Google. , пример приложения работает должным образом. Однако, когда я определяю свой собственный пакет приложения, после того, как пользователь разрешает разрешение приложения, браузер переходит на веб-сайт google.com вместо того, чтобы возвращаться к моей активности.

Я создал клиент OAuth 2.0 на консоли Google с типом Android и именем пакета com.x.y.

В моем манифесте:

<activity
        android:name=".ui.backup.BackupActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@style/LibraryTheme">
        <action android:name="com.x.y.HANDLE_AUTHORIZATION_RESPONSE"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </activity>

    <activity android:name="net.openid.appauth.RedirectUriReceiverActivity">
        <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="com.x.y"/>
        </intent-filter>
    </activity>

И код

private void setupAuthorization() {
    AuthorizationServiceConfiguration serviceConfiguration = new AuthorizationServiceConfiguration(
            Uri.parse("https://accounts.google.com/o/oauth2/v2/auth") /* auth endpoint */,
            Uri.parse("https://accounts.google.com/o/oauth2/token") /* token endpoint */
    );

    String clientId = "xxx.apps.googleusercontent.com";
    Uri redirectUri = Uri.parse("com.x.y:/oauth2callback");
    AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder(
            serviceConfiguration,
            clientId,
            AuthorizationRequest.RESPONSE_TYPE_CODE,
            redirectUri
    );
    builder.setScopes("https://www.googleapis.com/auth/drive");
    AuthorizationRequest request = builder.build();
    AuthorizationService authorizationService = new AuthorizationService(this);

    String action = "com.x.y.HANDLE_AUTHORIZATION_RESPONSE";
    Intent postAuthorizationIntent = new Intent(action);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, request.hashCode(), postAuthorizationIntent, 0);
        authorizationService.performAuthorizationRequest(request, pendingIntent);
}

Мне нужно использовать AppAuth для запроса "https://www.googleapis.com/auth/drive», аутентификация с помощью «Google Sign-in для Android» проще, но нет возможности предоставить это разрешение.


person thanhbinh84    schedule 17.07.2018    source источник


Ответы (1)


Я нашел способ использовать вход в Google для Android, чтобы получить разрешение на диск, поэтому больше не нужен сложный AppAuth.

private void setupAuthorization() {
    GoogleSignInOptions signInOptions =
            new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestScopes(new Scope("https://www.googleapis.com/auth/drive"))
                    .build();
    mGoogleSignInClient = GoogleSignIn.getClient(this, signInOptions);
    mGoogleSignInClient.silentSignIn().addOnSuccessListener(googleSignInAccount -> {
        handleGoogleSignedIn();
    }).addOnFailureListener(e -> {
        e.printStackTrace();
    });
}

private void handleGoogleSignedIn() {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            listFiles();
        }
    });
    thread.start();
}

private void listFiles() {
    GoogleAccountCredential credential =
            GoogleAccountCredential.usingOAuth2(
                    BackupActivity.this,
                    Collections.singleton(
                            "https://www.googleapis.com/auth/drive")
            );
    credential.setSelectedAccount(GoogleSignIn.getLastSignedInAccount(this).getAccount());

    Drive service = new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
            .setApplicationName(getString(R.string.app_name))
            .build();
    try {
        // Print the names and IDs for up to 10 files.
        FileList result = service.files().list()
                .setPageSize(10)
                .setFields("nextPageToken, files(id, name)")
                .execute();
        List<File> files = result.getFiles();
        if (files == null || files.isEmpty()) {
            System.out.println("No files found.");
        } else {
            System.out.println("Files:");
            for (File file : files) {
                System.out.printf("%s (%s)\n", file.getName(), file.getId());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void signInGdrive() {
    startActivityForResult(mGoogleSignInClient.getSignInIntent(), REQUEST_CODE_DRIVE_SIGN_IN);
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQUEST_CODE_DRIVE_SIGN_IN:
            if (resultCode == RESULT_OK) handleGoogleSignedIn();
            break;
    }
}

Подробности можно найти здесь

person thanhbinh84    schedule 18.07.2018