Once you have an OAuth 2.0 implementation, you can optionally configure
OAuth-based App Flip, which allows your iOS users to more
quickly link their accounts in your authentication system to their Google
Accounts. The following sections describe how to design and implement
App Flip for your Cloud-to-cloud integration on
iOS.

## 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](http://policies.google.com)
   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](https://myaccount.google.com) 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](https://www.google.com/permissions/logos-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.](https://developers.home.google.com/static/identity/images/app-flip-guidance.png) Figure 1: Account linking consent screen design guidelines.

## Set up for OAuth-based App Flip

The following sections describe the prerequisites for OAuth-based App Flip
and how to configure your App Flip project in the Google Home Developer
Console.

### Create a Cloud-to-cloud integration and set up an OAuth 2.0 server

Before you can configure App Flip, you need to do the
following:

- **Set up an OAuth 2.0 server.** For more information about setting up an OAuth server, see [Implement an OAuth 2.0
  server](https://developers.home.google.com/cloud-to-cloud/project/authorization).
- **Create a Cloud-to-cloud integration.** To create an integration, follow the instructions in [Create a Cloud-to-cloud
  integration](https://developers.home.google.com/cloud-to-cloud/integration/create).

### Configure App Flip in the Developer Console

The following section describes how to configure App Flip in the
[Developer Console](https://console.home.google.com/).

1. Fill out all the fields under **OAuth Client information** . (If App Flip isn't supported, regular OAuth is used as a fallback.)
2. Under **Use your app for account linking(optional)** , check **Enable
   for iOS**.
3. Fill out the **Universal Link** field. For more information about universal links, see [Allowing Apps and Websites to Link to
   your Content](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content).
4. If you want to optionally configure your client, add scopes and click **Add scope** under **Configure your client (optional).**
5. Click **Save**.


You can now continue to the next section to implement
App Flip in your
iOS
app.

## Implement App Flip in your native apps

To implement App Flip, you need to modify the user
authorization code in your app to accept a deep link from Google.

OAuth-based App Flip linking (App Flip) opens your iOS app from a Google app
to help the Google app user link their account more easily. You need to make
minor code changes to your iOS app to implement this feature.

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

### Try the sample

The App Flip [sample app](https://github.com/googlesamples/identity-appflip-ios)
demonstrates an account linking integration on iOS that's App Flip-compatible.
You can use this app to verify how to respond to an incoming App Flip universal
link from Google mobile apps.

The sample app is preconfigured to integrate with the [App Flip Test Tool for
iOS](https://github.com/googlesamples/identity-appflip-tester-ios),
which you can use to verify your iOS app's integration with App Flip before
you configure account linking with Google. This app simulates the universal link
triggered by Google mobile apps when App Flip is enabled.

### How it works

The following are the flow steps that the Google app and your app take when
App Flip occurs:

1. The Google app attempts to open your app's universal link. It's able to
   open your app if it's installed on the user's device and associated with
   the universal link. See [Supporting Universal Links](https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content) for details.

2. Your app checks that the `client_id` and `redirect_uri` parameter encoded
   in the incoming URL matches the expected Google universal link.

3. Your app requests an authorization code from your OAuth2 server. At the end
   of this flow, your app returns either an authorization code or an error to
   the Google app. To do this, it opens Google's universal link with appended
   parameters for the authorization code or error.

4. The Google app handles the incoming Google universal link and continues with
   the rest of the flow. If an authorization code is provided, the linking is
   completed immediately. The token exchange happens server-to-server, the same
   way it does in the browser-based OAuth linking flow. If an error code is
   returned, the linking flow continues with the alternative options.

### Modify your iOS app to support App Flip

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

1. Handle `NSUserActivityTypeBrowsingWeb` in your App Delegate.
2. Capture `redirect_uri` and `state` parameters from the URL to use later.
3. Check that `redirect_uri` matches this format:

   ```
   https://oauth-redirect.googleusercontent.com/a/GOOGLE_APP_BUNDLE_ID
   https://oauth-redirect-sandbox.googleusercontent.com/a/GOOGLE_APP_BUNDLE_ID
   ```
4. Verify that the client ID matches the expected value. Use the following
   code sample:

       func application(_ application: UIApplication,
                        continue userActivity: NSUserActivity,
                        restorationHandler: @escaping ([Any]?) -> Void) -> Bool
       {
           guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
               let incomingURL = userActivity.webpageURL,
               let components = URLComponents(url: incomingURL, resolvingAgainstBaseURL: false),
               let params = components.queryItems else {
                   return false
           }

           if let clientId = params.filter({$0.name == "client_id"}).first?.value,
               let state = params.filter({$0.name == "state"}).first?.value,
               let redirectUri = params.filter({$0.name == "redirect_uri"}).first?.value {

               // Save the redirect_uri and state for later...

               // Verify the client id
               return (clientId == GOOGLE_CLIENT_ID)
           } else {
               // Missing required parameters
               return false
           }
       }

5. Upon successful authorization, call the redirect URI with the authorization
   code. Use the following code sample:

       func returnAuthCode(code: String, state: String, redirectUri: String) {
           var redirectURL = URL(string: redirectUri)
           var components = URLComponents(url: redirectURL, resolvingAgainstBaseURL: false)

           // Return the authorization code and original state
           let paramAuthCode = URLQueryItem(name: "code", value: code)
           let paramState = URLQueryItem(name: "state", value: state)
           components?.queryItems = [paramAuthCode, paramState]
           if let resultURL = components?.url {
               UIApplication.shared.open(
                   resultURL,
                   options: [UIApplicationOpenURLOptionUniversalLinksOnly : true],
                   completionHandler: nil)
           }
       }

6. If an error occurred, attach an error result to the redirect URI instead.
   Use the following code sample:

   > [!NOTE]
   > **Note:** Do not handle the error directly within your app, instead return the error result to the `REDIRECT_URL`. This ensures that the appropriate fallback method is triggered if the app linking flow fails.

       func returnError(redirectUri: String) {
           var redirectURL = URL(string: redirectUri)
           var components = URLComponents(url: redirectURL, resolvingAgainstBaseURL: false)

           // Return the authorization code and original state
           let paramError = URLQueryItem(name: "error", value: "invalid_request")
           let paramDescription = URLQueryItem(name: "error_description", value: "Invalid Request")
           components?.queryItems = [paramError, paramDescription]
           if let resultURL = components?.url {
               UIApplication.shared.open(
                   resultURL,
                   options: [UIApplicationOpenURLOptionUniversalLinksOnly : true],
                   completionHandler: nil)
           }
       }

### Query parameters for your app's universal link

When opened by the Google app, your app's universal link includes the following
query parameters:

- `client_id` (`String`): Google `client_id` that's registered under your app.
- `scope` (`List of String`): A list of space-separated scopes requested.
- `state` (`String`): A nonce used by Google to verify that the authorization result is in response to Google's outgoing request.
- `redirect_uri` (`String`): Google's universal link. The "flip" URI to open the Google app and pass results.

### Query parameters for Google's universal link

Parameters used when the authorization result is returned successfully:

- `code` (`String`): The value of the authorization code, if available.
- `state` (`String`): The exact value received from the incoming universal link.

Parameters used when the authorization result is returned unsuccessfully:

- `error` (`String`), with the following values:

  - `cancelled`: A recoverable error. The Google app will attempt account linking using the authorization URL. Some examples are the user failing to sign in, a device being offline or a connection timing out.
  - `unrecoverable`: An unrecoverable error. For example, the user attempts to link with a disabled account.The Google app will abort account linking.
  - `invalid_request`: The request parameters are invalid or missing. This is a recoverable error. The Google app will attempt account linking using the authorization URL.
  - `access_denied`: The user rejects the consent request. This is a non-recoverable error; the Google app aborts linking.
- `error_description` (`String`, optional): A user-friendly error message.

  > [!NOTE]
  > **Note:** For more information on [possible errors](https://www.oauth.com/oauth2-servers/server-side-apps/possible-errors/) and the optional contents of the `error_description` field, see the OAuth 2.0 standard.

For all error types, you must return the response data to the specified
`REDIRECT_URI` to ensure the appropriate fallback is triggered.

### Modify your authorization endpoint to support App Flip

Configure your platform to accept requests using Google's App Flip redirect URLs:

- Google Home app

  ```
  https://oauth-redirect.googleusercontent.com/a/com.google.Chromecast.dev
  https://oauth-redirect.googleusercontent.com/a/com.google.Chromecast.enterprise
  https://oauth-redirect.googleusercontent.com/a/com.google.Chromecast
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.Chromecast.dev
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.Chromecast.enterprise
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.Chromecast
  ```
- Google Assistant app

  ```
  https://oauth-redirect.googleusercontent.com/a/com.google.OPA.dev
  https://oauth-redirect.googleusercontent.com/a/com.google.OPA.enterprise
  https://oauth-redirect.googleusercontent.com/a/com.google.OPA
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.OPA.dev
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.OPA.enterprise
  https://oauth-redirect-sandbox.googleusercontent.com/a/com.google.OPA
  ```

For the Google Home app (GHA), Smart Home account linking uses the
`com.google.Chromecast` redirect URLs. Ensure your authorization server allows
these redirect URLs.

Check that `client_id` and the URL specified by the `redirect_uri` parameter
match the expected values when a request is received. If the client verification
fails, return the error `invalid_request` to the `redirect_uri`.

## Test App Flip on your device

Now that you've created a Cloud-to-cloud integration and configured App Flip
on the console and in your app, you can test App Flip on your mobile device.
You can use the Google Home app to test App Flip.

To test App Flip from the Google Home app,
follow these steps:

> [!NOTE]
> **Note:** Make sure that you are signed in to the Google Home app with your test account.

1. Go to the [Developer Console](https://console.home.google.com/) and select your project.
2. Go to **Cloud-to-cloud \> Test**.
3. Trigger the account linking flow from the Home app:
   1. Open the [Google Home app (GHA)](https://play.google.com/store/apps/details?id=com.google.android.apps.chromecast.app).
   2. Click the **+** button.
   3. Click **Set up device**.
   4. Click **Have something already set up?**
   5. Select your Cloud-to-cloud integration from the list of providers. It will be prefixed with "\[test\]" in the list. When you select your \[test\] integration from the list, it should open your app.
   6. Verify that your app was launched and begin testing your authorization flow.