Android용 앱 플립

OAuth 2.0 구현이 완료되면 원하는 경우 OAuth 기반 App Flip를 구성할 수 있습니다. 이를 통해 Android 사용자는 인증 시스템의 계정을 Google 계정에 더 빠르게 연결할 수 있습니다. 다음 섹션에서는 Android에서 Cloud-to-cloud 통합을 위한 App Flip를 설계하고 구현하는 방법을 설명합니다.

Design guidelines

This section describes the design requirements and recommendations for the App Flip account linking consent screen. After Google calls your app, your app displays the consent screen to the user.

Requirements

  1. You must have a Google authorization statement such as "Once linked, Google will have permission to control your devices."
  2. You must communicate that the user's account is being linked to Google, not to a specific Google product, such as Google Home or Google Assistant.
  3. You must state a clear call-to-action on your consent screen and use the wording "Agree and link" for linking action. This is because users need to understand what data they're required to share with Google to link their accounts.
  4. You must provide a way for users to go back, deny or cancel, if they choose not to link. Use the wording "Cancel" for the cancel action.
  5. You must implement this workflow: After clicking "Agree and link", you must show linking success and redirect the user back to the Google Home app automatically. The user should now see the linked device on the Google Home app with your action. After clicking "Cancel" you should redirect the user back to the Google Home app.

Recommendations

We recommend that you do the following:

  1. Display Google's Privacy Policy. Include a link to Google's Privacy Policy on the consent screen.

  2. Data to be shared. Use clear and concise language to tell the user what data of theirs Google requires and why.

  3. Ability to unlink. Offer a mechanism for users to unlink, such as a URL to their account settings on your platform. Alternatively, you can include a link to Google Account where users can manage their linked account.

  4. Ability to change user account. Suggest a method for users to switch their account(s). This is especially beneficial if users tend to have multiple accounts.

    • If a user must close the consent screen to switch accounts, send a recoverable error to Google so the user can sign in to the desired account with OAuth linking and the implicit flow.
  5. Include your logo. Display your company logo on the consent screen. Use your style guidelines to place your logo. If you wish to also display Google's logo, see Logos and trademarks.

This figure shows an example consent screen with call-outs to the
            individual requirements and recommendations to be followed when
            you design a user consent screen.
Figure 1: Account linking consent screen design guidelines.

OAuth 기반 App Flip 설정

다음 섹션에서는 OAuth 기반 앱 전환의 기본 요건과 Google Home Developer Console에서 앱 전환 프로젝트를 구성하는 방법을 설명합니다.

Cloud-to-Cloud 통합을 만들고 OAuth 2.0 서버 설정

App Flip를 구성하려면 먼저 다음을 수행해야 합니다.

Play Console에서 앱 전환 구성

다음 섹션에서는 Developer Console에서 앱 전환을 구성하는 방법을 설명합니다.

  1. 계정 연결에서 필수(*) 입력란을 모두 작성합니다. (앱 전환이 지원되지 않는 경우 일반 OAuth가 대체로 사용됩니다.)
  2. Cloud 처리 URL의 URL을 입력합니다. 클라우드 처리 URL은 스마트 홈 인텐트를 처리하는 데 사용됩니다. 로컬 처리를 선택합니다.
  3. 앱 전환 (선택사항)에서 Android 앱을 선택합니다.
  4. 다음 입력란을 작성합니다.
    • 애플리케이션 ID 애플리케이션 ID는 앱에 설정하는 고유 ID입니다.
    • 앱 서명. Android 앱은 설치하기 전에 공개 키 인증서로 '서명'해야 합니다. 앱 서명을 가져오는 방법에 관한 자세한 내용은 클라이언트 인증을 참고하세요.
    • 승인 인텐트 이 필드에 인텐트 작업을 지정하는 문자열을 입력합니다.
  5. 클라이언트를 선택적으로 구성하려면 범위를 추가하고 범위(선택사항)에서 범위 추가를 클릭합니다.
  6. 클라이언트에 필요한 경우 Google에서 HTTP 기본 인증 헤더를 통해 클라이언트 ID 및 보안 비밀번호를 전송하도록 설정을 선택합니다.

이제 다음 섹션으로 이동하여 Android 앱에 App Flip를 구현할 수 있습니다.

네이티브 앱에 App Flip 구현

App Flip를 구현하려면 Google의 딥 링크를 허용하도록 앱의 사용자 승인 코드를 수정해야 합니다.

OAuth-based App Flip linking (App Flip) inserts your Android app into the Google Account Linking flow. A traditional account linking flow requires the user to enter their credentials in the browser. The use of App Flip defers user sign-in to your Android app, which allows you to leverage existing authorizations. If the user is signed in to your app, they don't need to re-enter their credentials to link their account. A minimal amount of code changes are required to implement App Flip on your Android app.

In this document, you learn how to modify your Android app to support App Flip.

Try the sample

The App Flip linking sample app demonstrates an App Flip-compatible account linking integration on Android. You can use this app to verify how to respond to an incoming App Flip intent from Google mobile apps.

The sample app is preconfigured to integrate with the App Flip Test Tool for Android, which you can use to verify your Android app's integration with App Flip before you configure account linking with Google. This app simulates the intent triggered by Google mobile apps when App Flip is enabled.

How it works

The following steps are required to carry out an App Flip integration:

  1. The Google app checks if your app is installed on the device using its package name.
  2. The Google app uses a package signature check to validate that the installed app is the correct app.
  3. The Google app builds an intent to start a designated activity in your app. This intent includes additional data required for linking. It also checks to see if your app supports App Flip by resolving this intent through the Android framework.
  4. Your app validates that the request is coming from the Google app. To do so, your app checks the package signature and the provided client ID.
  5. Your app requests an authorization code from your OAuth 2.0 server. At the end of this flow, it returns either an authorization code or an error to the Google app.
  6. The Google app retrieves the result and continues with account linking. If an authorization code is provided, the token exchange happens server-to-server, the same way it does in the browser-based OAuth linking flow.

Modify your Android app to support App Flip

To support App Flip, make the following code changes to your Android app:

  1. Add an <intent-filter> to your AndroidManifest.xml file with an action string that matches the value you entered in the App Flip Intent field.

    <activity android:name="AuthActivity">
      <!-- Handle the app flip intent -->
      <intent-filter>
        <action android:name="INTENT_ACTION_FROM_CONSOLE"/>
        <category android:name="android.intent.category.DEFAULT"/>
      </intent-filter>
    </activity>
    
  2. Validate the calling app's signature.

    You need to match the package name and signature for any Google apps that users may use to account link. For example, to link with Google Home and Search apps, add their package names and signatures:

    • Package name: com.google.android.apps.chromecast.app
    • Original SHA-256 lineage certificate: 3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A
    • Rotated Play App Signing SHA-256 certificate: 5A:AD:2B:EE:6D:B9:5D:17:E0:5A:08:D7:D1:E6:4C:10:A1:51:18:79:15:44:83:91:6B:6A:E6:C7:FD:9C:B0:C6

    and

    • Package name: com.google.android.googlequicksearchbox
    • Signature: F0:FD:6C:5B:41:0F:25:CB:25:C3:B5:33:46:C8:97:2F:AE:30:F8:EE:74:11:DF:91:04:80:AD:6B:2D:60:DB:83

    Smart home linking requests are initiated directly by the Google Home app (GHA). If your application restricts callers and previously only allowed the Google Search app, you must add com.google.android.apps.chromecast.app and its SHA-256 certificates to your allowlist so that App Flip continues to succeed.

    private fun verifyFingerprint(
        expectedPackage: String,
        expectedFingerprints: List<String>
    ): Boolean {
        val callingPackage = callingActivity?.packageName ?: return false
        if (callingPackage != expectedPackage) return false
        return expectedFingerprints.any { hex ->
            val sha256Bytes =
                hex.split(":").map { it.toInt(16).toByte() }.toByteArray()
            packageManager.hasSigningCertificate(
                callingPackage,
                sha256Bytes,
                PackageManager.CERT_INPUT_SHA256
            )
        }
    }
    
  3. Extract the client ID from the intent parameters and verify that the client ID matches the expected value.

    private const val EXPECTED_CLIENT = "<client-id-from-actions-console>"
    private const val EXPECTED_PACKAGE = "com.google.android.apps.chromecast.app"
    // Original lineage certificate (3D:7A...) and active rotated
    // Play App Signing certificate (5A:AD...)
    private val EXPECTED_FINGERPRINTS = listOf(
        "3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A",
        "5A:AD:2B:EE:6D:B9:5D:17:E0:5A:08:D7:D1:E6:4C:10:A1:51:18:79:15:44:83:91:6B:6A:E6:C7:FD:9C:B0:C6"
    )
    ...
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        val clientId = intent.getStringExtra("CLIENT_ID")
    
        if (clientId == EXPECTED_CLIENT &&
            verifyFingerprint(EXPECTED_PACKAGE, EXPECTED_FINGERPRINTS)) {
    
            // ...authorize the user...
        }
    }
    
  4. Upon successful authorization, return the resulting authorization code back to Google.

    // Successful result
    val data = Intent().apply {
        putExtra("AUTHORIZATION_CODE", authCode)
    }
    setResult(Activity.RESULT_OK, data)
    finish()
    
  5. If an error occurred, return an error result instead.

    // Error result
    val error = Intent().apply {
        putExtra("ERROR_TYPE", 1)
        putExtra("ERROR_CODE", 1)
        putExtra("ERROR_DESCRIPTION", "Invalid Request")
    }
    setResult(-2, error)
    finish()
    

Content of the launch intent

The Android intent that launches your app includes the following fields:

  • CLIENT_ID (String): Google client_id registered under your app.
  • SCOPE (String[]): A list of scopes requested.
  • REDIRECT_URI (String): The redirect URL.

Content of the response data

The data returned to the Google app is set in your app by calling setResult(). This data includes the following:

  • AUTHORIZATION_CODE (String): The authorization code value.
  • resultCode (int): Communicates the success or failure of the process and takes one of the following values:
    • Activity.RESULT_OK: Indicates success; an authorization code is returned.
    • Activity.RESULT_CANCELLED: A recoverable error. Signals that the user has cancelled the process. In this case, the Google app will attempt account linking again using your authorization URL.
    • -2: Indicates that an error has occurred. Different types of errors are described below.
  • ERROR_TYPE (int): The type of error, which takes one of the following values:
    • 1: Recoverable error: The Google app will attempt account linking using the authorization URL.
    • 2: Unrecoverable error: The Google app aborts account linking.
    • 3: Invalid or missing request parameters.
  • ERROR_CODE (int): An integer representing the nature of the error. To see what each error code means, refer to the table of error codes.
  • ERROR_DESCRIPTION (String, optional): Human-readable status message describing the error.

A value for the AUTHORIZATION_CODE is expected when resultCode == Activity.RESULT_OK. In all other cases, the value for AUTHORIZATION_CODE needs to be empty. If resultCode == -2, then the ERROR_TYPE value is expected to be populated.

Table of error codes

The table below shows the different error codes and whether each is a recoverable or unrecoverable error:

Error code Meaning Recoverable Unrecoverable
1 INVALID_REQUEST ✔
2 NO_INTERNET_CONNECTION ✔
3 OFFLINE_MODE_ACTIVE ✔
4 CONNECTION_TIMEOUT ✔
5 INTERNAL_ERROR ✔
6 AUTHENTICATION_SERVICE_UNAVAILABLE ✔
8 CLIENT_VERIFICATION_FAILED ✔
9 INVALID_CLIENT ✔
10 INVALID_APP_ID ✔
11 INVALID_REQUEST ✔
12 AUTHENTICATION_SERVICE_UNKNOWN_ERROR ✔
13 AUTHENTICATION_DENIED_BY_USER ✔
14 CANCELLED_BY_USER ✔
15 FAILURE_OTHER ✔
16 USER_AUTHENTICATION_FAILED ✔

For all error codes, you must return the error result via setResult to ensure the appropriate fallback is triggered.

기기에서 App Flip 테스트

클라우드 간 통합을 만들고 콘솔과 앱에서 앱 전환을 구성했으므로 이제 휴대기기에서 앱 전환을 테스트할 수 있습니다. Google Home 앱을 사용하여 앱 전환을 테스트할 수 있습니다.

Google Home 앱에서 App Flip를 테스트하려면 다음 단계를 따르세요.

  1. Developer Console로 이동하여 프로젝트를 선택합니다.
  2. Cloud-to-cloud > Test로 이동합니다.
  3. Home 앱에서 계정 연결 흐름을 트리거합니다.
    1. Google Home app (GHA)를 엽니다.
    2. 화면의 + 버튼을 클릭합니다.
    3. 장치 설정을 클릭하세요.
    4. I have already set up my Google Ads account. How do I link it to my YouTube channel?
    5. 제공업체 목록에서 클라우드 간 통합을 선택합니다. 목록에서 '[test]'가 프리픽스로 추가됩니다. 목록에서 [테스트] 통합을 선택하면 앱이 열립니다.
    6. 앱이 실행되었는지 확인하고 승인 흐름 테스트를 시작합니다.