# Signing in users with OIDC

This document shows you how to use Identity Platform to sign in users with an
OpenID Connect (OIDC) provider.

## Before you begin

1. Enable Identity Platform, and add the client SDK to your app. See the [Quickstart](https://docs.cloud.google.com/identity-platform/docs/sign-in-user-email.md.txt) to learn how.

## Configuring the provider

1. Go to the **Identity Providers** page in the Google Cloud console.  

   [Go to the Identity Providers page](https://console.cloud.google.com/customer-identity/providers)  

2. Click **Add a Provider** , and select **OpenID Connect** from the list.

### Authorization Code Flow

1. Enter the following details to enable the Authorization Code Flow:

   1. Select **Code Flow** under **Choose grant type** section.

   2. The **Name** of the provider. This can be the same as the provider ID,
      or a custom name. If you enter a custom name, click **Edit** next to
      **Provider ID** to specify the ID (which must begin with `oidc.`).

   3. The provider's **Client ID**.

   4. The provider's **Issuer** . This should look something like
      `https://example.com`. Identity Platform uses this URL to locate
      the OIDC discovery document (typically found at
      `/.well-known/openid-configuration`), which specifies the provider's
      OAuth endpoints and public keys.

      > [!NOTE]
      > **Note:** If your OIDC provider doesn't comply with the [OIDC specification](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) for discovery, it won't work with Identity Platform.

   5. The provider's **Client Secret**.

2. Add your app to the list of **Authorized Domains** . For example, if your
   app's sign-in URL is `https://example.com/login`, add `example.com`.

3. Configure the Identity Platform callback URL as a redirect URL with
   your OIDC provider. The URL should look similar to
   `https://[PROJECT-ID].firebaseapp.com/__/auth/handler`.

4. Click **Save**.

### Implicit Flow

1. Enter the following details to enable the Implicit Flow:

   1. Select **Implicit Flow** under **Choose grant type** section.

   2. The **Name** of the provider. This can be the same as the provider ID,
      or a custom name. If you enter a custom name, click **Edit** next to
      **Provider ID** to specify the ID (which must begin with `oidc.`).

   3. The provider's **Client ID**.

   4. The provider's **Issuer** . This should look something like
      `https://example.com.` Identity Platform uses this URL to locate
      the OIDC discovery document (typically found at
      `/.well-known/openid-configuration`), which specifies the provider's
      OAuth endpoints and public keys.

      > [!NOTE]
      > **Note:** If your OIDC provider doesn't comply with the [OIDC specification](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig) for discovery, it won't work with Identity Platform.

2. Add your app to the list of **Authorized Domains** . For example, if your
   app's sign-in URL is `https://example.com/login`, add `example.com`.

3. Configure the Identity Platform callback URL as a redirect URL with
   your OIDC provider. The URL should look similar to
   `https://[PROJECT-ID].firebaseapp.com/__/auth/handler`.

4. Click **Save**.

## Signing in users

There are two ways to sign in users with OIDC:

- Using OAuth flow. This way completes the OAuth handshake for you. Based
  on the Authorization Code Flow/Implicit Flow selection at the configuring
  provider step, GCIP server chooses the desired flow to communicate with the
  Identity Provider.

- Using the OIDC provider's ID token. This way assumes you already have an
  OIDC token available.

### Signing in users with OAuth

To sign in using OAuth:

1. Create an [`OAuthProvider`](https://firebase.google.com/docs/reference/js/v8/firebase.auth.OAuthProvider)
   instance with the provider ID you configured in
   the previous section. The provider ID must start with `oidc.`.

   ### Web version 9

   ```javascript
   import { OAuthProvider } from "firebase/auth";

   const provider = new OAuthProvider("oidc.myProvider");
   ```

   ### Web version 8

   ```javascript
   const provider = new firebase.auth.OAuthProvider('oidc.myProvider');
   ```
2. Start the sign in flow. You can choose to either use a popup or a redirect.

   ### Popup

   ### Web version 9

   ```javascript
   import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";

   const auth = getAuth();
   signInWithPopup(auth, provider)
     .then((result) => {
       // User is signed in.
       const credential = OAuthProvider.credentialFromResult(result);
       // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider
     }).catch((error) => {
       // Handle Errors here.
       const errorCode = error.code;
       const errorMessage = error.message;
       // The email of the user's account used.
       const email = error.customData.email;
       // The AuthCredential type that was used.
       const credential = OAuthProvider.credentialFromError(error);
       // Handle / display error.
       // ...
     });
   ```

   ### Web version 8

   ```javascript
   firebase.auth().signInWithPopup(provider)
     .then((result) => {
       // User is signed in.
       // result.credential is a firebase.auth().OAuthCredential object.
       // result.credential.providerId is equal to 'oidc.myProvider'.
       // result.credential.idToken is the OIDC provider's ID token.
     })
     .catch((error) => {
       // Handle error.
     });
   ```

   ### Redirect

   To redirect to a sign-in page, call `signInWithRedirect()`:

   ### Web version 9

   ```javascript
   import { getAuth, signInWithRedirect } from "firebase/auth";

   const auth = getAuth();
   signInWithRedirect(auth, provider);
   ```

   ### Web version 8

   ```javascript
   firebase.auth().signInWithRedirect(provider).catch((error) => {
     // Handle error.
   });
   ```

   Then, call `getRedirectResult()` to get the results when the user returns to your app:

   ### Web version 9

   ```javascript
   import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";

   const auth = getAuth();
   getRedirectResult(auth)
     .then((result) => {
       // User is signed in.
       const credential = OAuthProvider.credentialFromResult(result);
       // This gives you an access token for the OIDC provider. You can use it to directly interact with that provider
     })
     .catch((error) => {
       // Handle Errors here.
       const errorCode = error.code;
       const errorMessage = error.message;
       // The email of the user's account used.
       const email = error.customData.email;
       // The AuthCredential type that was used.
       const credential = OAuthProvider.credentialFromError(error);
       // Handle / display error.
       // ...
     });
   ```

   ### Web version 8

   ```javascript
   // On return.
   firebase.auth().getRedirectResult()
     .then((result) => {
       // User is signed in.
       // result.credential is a firebase.auth().OAuthCredential object.
       // result.credential.providerId is equal to 'oidc.myProvider'.
       // result.credential.idToken is the OIDC provider's ID token.
     })
     .catch((error) => {
       // Handle / display error.
       // ...
     });
   ```

At the conclusion of either flow, you can get the OIDC ID token using the
`result.credential.idToken` field.

### Signing in users directly

To sign a user in with an OIDC ID token directly, do the following:

1. Initialize an `OAuthProvider` instance with the provider ID you configured in the previous section. The provider ID must start with `oidc.`. Then, create an `OAuthCredential`, and call `signInWithCredential()` to sign the user in.

   ### Web version 9

   ```javascript
   import { getAuth, OAuthProvider, signInWithCredential } from "firebase/auth";

   const auth = getAuth();
   const credential = provider.credential({
     idToken: oidcIdToken,
   });
   signInWithCredential(auth, credential)
     .then((result) => {
       // User is signed in.
       const newCredential = OAuthProvider.credentialFromResult(result);
       // This gives you a new access token for the OIDC provider. You can use it to directly interact with that provider.
     })
     .catch((error) => {
       // Handle Errors here.
       const errorCode = error.code;
       const errorMessage = error.message;
       // The email of the user's account used.
       const email = error.customData.email;
       // The AuthCredential type that was used.
       const credential = OAuthProvider.credentialFromError(error);
       // Handle / display error.
       // ...
     });
   ```

   ### Web version 8

   ```javascript
   const credential = provider.credential(oidcIdToken, null);

   firebase.auth().signInWithCredential(credential)
     .then((result) => {
       // User is signed in.
       // User now has a odic.myProvider UserInfo in providerData.
     })
     .catch((error) => {
       // Handle / display error.
       // ...
     });
   ```

## Linking user accounts

If a user has already signed in to your app using a different method (such as email/password), you can [link their existing account](https://docs.cloud.google.com/identity-platform/docs/link-accounts.md.txt) to the OIDC provider using `linkWithPopup()` or `linkWithRedirect()`:
For example we can link with a Google account:

### Web version 9

```javascript
import { getAuth, linkWithPopup, GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider();

const auth = getAuth();
linkWithPopup(auth.currentUser, provider).then((result) => {
  // Accounts successfully linked.
  const credential = GoogleAuthProvider.credentialFromResult(result);
  const user = result.user;
  // ...
}).catch((error) => {
  // Handle Errors here.
  // ...
});
```

### Web version 8

```javascript
auth.currentUser.linkWithPopup(provider).then((result) => {
  // Accounts successfully linked.
  var credential = result.credential;
  var user = result.user;
  // ...
}).catch((error) => {
  // Handle Errors here.
  // ...
});
```

## What's next

- [Signing in users with SAML](https://docs.cloud.google.com/identity-platform/docs/web/saml.md.txt)
- [Showing a custom domain during sign in](https://docs.cloud.google.com/identity-platform/docs/show-custom-domain.md.txt)
- [Managing OIDC and SAML providers programmatically](https://docs.cloud.google.com/identity-platform/docs/managing-providers-programmatically.md.txt)