---
id: google
title: Add Google as a social sign-in provider in Ory
sidebar_label: Google
---

# Google

:::note

To add Google as a social sign-in provider, you need a Google Developer account. Go to
[Google Cloud Console](https://console.developers.google.com/) to create one.

:::

````mdx-code-block
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs>
<TabItem value="console" label="Ory Console" default>

Follow these steps to add Google as a social sign-in provider to your project using the Ory Console:

1. Go to <ConsoleLink route="project.socialSignIn" />.
2. Click the switch next to the Google logo to start the configuration.
3. Copy the Redirect URI and save it for later use.
4. Go to [Google Cloud Console → APIs & Services](https://console.cloud.google.com/apis/) to set up OAuth 2.
5. Using the project dropdown menu, select an existing project or create a new one.
6. Go to [Credentials](https://console.cloud.google.com/apis/credentials) and create a new
   [OAuth client ID](https://console.cloud.google.com/apis/credentials/oauthclient). You must have a consent screen configured to proceed.
7. Configure the Google OAuth client. In the **Authorized redirect URIs** section, add the redirect URI copied from the Ory
   Console.
8. Save the configuration and copy the Client ID and Client secret.
9. Paste the Client ID and Client secret of the created OAuth client into the corresponding fields in the Ory Console.
10. Click **Save Configuration** to enable Google as a social sign-in provider.

:::note

These steps cover the basic configuration of a social sign-in provider integration. At this point, the user experience is
incomplete. To complete the configuration and ensure a smooth and secure user experience, configure the [scopes](#scopes) and
[data mapping](#data-mapping) as described in the next section.

:::

## Additional configuration

When adding a social sign-in provider, you can customize the integration by defining the OAuth scopes Ory requests from the
provider and by setting up custom data mappings.

### Scopes

The Scopes section allows you to define the OAuth scopes Ory requests from the sign-in provider. Defining scopes allows you to
interact with the provider's APIs on behalf of the user, or to access additional user data, which is exposed as claims for data
mapping.

For Google, add the `email` and `profile` scopes for a basic setup.

To learn more about the scopes available for Google, read the
[related documentation](https://developers.google.com/identity/protocols/oauth2/scopes).

### Data mapping

The **Data mapping** section allows you to map the data returned by the sign-in provider to traits as defined in the identity
schema.

To define the mapping, create a Jsonnet code snippet. Read [this document](./data-mapping) to learn more about Jsonnet data
mapping.

```jsonnet
local claims = {
  email_verified: false,
} + std.extVar('claims');

{
  identity: {
    traits: {
      [if 'email' in claims && claims.email_verified then 'email' else null]: claims.email,
      // Google can return the user's full name as a single string.
      // Make sure to adjust your identity schema to store the first and last name as separate traits.
      // first_name: claims.given_name,
      // last_name: claims.family_name,
      //
      // hd is the hosted domain of the user's email address.
      // [if 'hd' in claims && claims.email_verified then 'hd' else null]: claims.hd,    },
  },
}
```

The sample Jsonnet snippet creates the following mapping:

| Google claim | Ory Identity schema mapping |
| :----------- | :-------------------------- |
| email        | email                       |
| given_name   | first_name                  |
| family_name  | last_name                   |

:::note

If you want to use this data mapping, you must include the `first_name` and `last_name` fields in your Identity Schema

:::

```mdx-code-block
import JsonnetWarning from '../../_common/jsonnetwarning.mdx'

<JsonnetWarning />
```

:::tip

For Google, you can use the `hd` claim which is the hosted Google Workplace domain of the user. This claim is used only when the
user has a Google Workspace account.

To learn more about the ID payload returned by Google, read the
[related documentation](https://developers.google.com/identity/protocols/oauth2/openid-connect#an-id-tokens-payload).

:::

</TabItem>
<TabItem value="cli" label="Ory CLI">

Follow these steps to add Google as a social sign-in provider to your project using the Ory CLI:

1. Create a Google OAuth client.
2. Create a Jsonnet code snippet to map the desired claims to the Ory Identity schema.

    ```jsonnet
    local claims = {
      email_verified: false,
    } + std.extVar('claims');

    {
      identity: {
        traits: {
          [if 'email' in claims && claims.email_verified then 'email' else null]: claims.email,
          first_name: claims.given_name,
          last_name: claims.family_name,
          [if 'hd' in claims && claims.email_verified then 'hd' else null]: claims.hd,
        },
      },
    }
    ```

    The sample Jsonnet snippet creates the following mapping:

    | Google claim | Ory Identity schema mapping |
    | :----------- | :-------------------------- |
    | email        | email                       |
    | given_name   | first_name                  |
    | family_name  | last_name                   |

    :::note

    If you want to use this data mapping, you must include the `first_name` and `last_name` fields in your Identity Schema

    :::

3. Encode the Jsonnet snippet with [Base64](https://www.base64encode.org/) or host it under an URL accessible to Ory Network.

  ```shell
  cat your-data-mapping.jsonnet | base64
  ```

4. Download the Ory Identities config from your project and save it to a file:

   ```shell
   ## List all available workspaces
   ory list workspaces

   ## List all available projects
   ory list projects --workspace <workspace-id>

   ## Get config
   ory get identity-config --project <project-id> --workspace <workspace-id> --format yaml > identity-config.yaml
   ```

5. Add the social sign-in provider configuration to the downloaded config. Add the Jsonnet snippet with mappings as a Base64
   string or provide an URL to the file.

   ```yaml
   selfservice:
     methods:
       oidc:
         config:
           providers:
             - id: google # this is `<provider-id>` in the Authorization callback URL. DO NOT CHANGE IT ONCE SET!
               provider: google
               client_id: .... # Replace this with the OAuth2 Client ID
               client_secret: .... # Replace this with the OAuth2 Client secret
               mapper_url: "base64://{YOUR_BASE64_ENCODED_JSONNET_HERE}"
               # Alternatively, use an URL:
               # mapper_url: https://storage.googleapis.com/abc-cde-prd/9cac9717f007808bf17f22ce7f4295c739604b183f05ac4afb4
               scope:
                 - email
                 - profile
               # other supported scopes can be found in Google OAuth 2.0 dev docs
               requested_claims:
                 id_token:
                   email:
                     essential: true
                   email_verified:
                     essential: true
                   given_name:
                     essential: true
                   family_name: null
                   hd: null # If you want the Google Workspace domain
         enabled: true
   ```

6. Update the Ory Identities configuration using the file you worked with:

   ```shell
   ory update identity-config --file iden--project <project-id> --workspace <workspace-id>tity-config.yaml
   ```

</TabItem>
</Tabs>
````

### Additional Parameters

The following parameters are available for the Google provider:

- `login_hint`
- `hd`

The `login_hint` parameter suppresses the account chooser and either pre-fills the email box on the sign-in form, or selects the
proper session. The `hd` parameter limits the login/registration process to a Google Organization, for example `mycollege.edu`.

The parameters can be passed along to Ory on `login`, `registration` and `settings` flows on form submit.

See the [Advanced Integration](../bring-your-own-ui/10_custom-ui-advanced-integration.mdx#upstream-provider-parameters) document for more
information on passing parameters from your UI to Ory.

### Account linking

Google supports [automatic account linking](./link-multiple-provider-account#automatic-account-linking-for-google-and-apple). When
enabled, users who sign in with a Google consumer account (`gmail.com`) that shares a verified email with an existing identity are
automatically linked without additional verification.

Automatic account linking is not available for Google Workspace accounts because expired domains can be re-registered by an
attacker.

To enable automatic account linking, set `account_linking_mode` to `automatic` in the provider configuration. Read the
[account linking documentation](./link-multiple-provider-account#enable-automatic-account-linking) for setup instructions.

## Using the Google SDK on native apps

Google provides a more integrated UX for native apps using the
[Google SDK](https://developers.google.com/identity/sign-in/web/backend-auth). This flow uses the native Google SDK and does not
require a browser. This results in a signed `id_token` on the client side (typically your app) which is exchanged at Ory for a
session token.

The following steps are required to integrate the Google SDK with Ory:

1. Configure a Google social sign-in provider in Ory using the same `client_id` as used in your native app.
2. Optional: Android apps generate different token audiences per distribution (debug, release, etc.). You can add the ID of your
   current distribution to the `additional_id_token_audiences` field. Example: `sh.ory.network-example-ios.debug`.
3. If your SDK supports nonce validation, make sure to use a generated value and submit that during the next step.
4. Obtain an `id_token` from Google using the Google SDK. Make sure to also submit the `nonce` if you generated one in the step
   before.
5. Submit the `id_token` and `nonce` (as the `id_token_nonce`) as part of the `updateRegistrationFlow` or `updateLoginFlow`
   request to Ory.
6. Ory will validate the `id_token` and create an identity and optionally a session (if configured).

The `id_token` is verified using Google's publicly available signing keys, available under
https://www.googleapis.com/oauth2/v3/certs.

Make sure to request the scopes you require in your Jsonnet mapping, otherwise they will be empty after the registration. Ory
doesn't communicate directly with Google during this flow and doesn't have access to the Access & Refresh Tokens. This means that
Ory cannot return these in the admin APIs or SDK.

:::danger

While not explicitly required, as not all of Google SDKs support it, Ory recommends that you use a `nonce` to prevent replay
attacks wherever possible.

:::

### Flutter code example

The following showcases an example implementation of a Sign in with Google button using the Ory SDK and
[google_sign_in](https://pub.dev/packages/google_sign_in) Flutter package.

```mdx-code-block
import CodeBlock from '@theme/CodeBlock'
import signInWithGoogleSnippet from "!!raw-loader!@site/code-examples/sdk/dart/social-sign-in/sign-in-with-google.dart"

<CodeBlock language="dart" title="sign-in-with-google.dart">{signInWithGoogleSnippet}</CodeBlock>
```

## Troubleshooting

```mdx-code-block
import SocialSigninTroubleshooting from '../_common/social-sign-in-troubleshooting.mdx'

<SocialSigninTroubleshooting />
```

### Error: token audience didn't match allowed audiences

Make sure to either add your apps current identifier to the `additional_id_token_audiences` field or set it as the Client ID of
the provider in the Ory Console.
