# Signing in users with SAML

This document shows you how to use Identity Platform to sign in users with a
Security Assertion Markup Language (SAML) 2.0 provider.

## Before you begin

1. Enable Identity Platform, and add the client SDK to your app. For more information and instructions, see the [Sign in a user with an email by using Identity Platform](https://docs.cloud.google.com/identity-platform/docs/sign-in-user-email.md.txt) quickstart.

## Configure the provider

1. In the Google Cloud console, go to the **Identity Platform \> Identity providers** page.  

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

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

3. Enter the following details:

   1. 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 `saml`).

   2. The provider's **Entity ID**.

   3. The provider's **SAML SSO URL**.

   4. The certificate used for token-signing on the provider. Make sure to
      include the start and end strings. For example:

      ```
      ---BEGIN CERTIFICATE---
      MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czEL
      ...
      LEzc1JwEGQQVDYQCwsQMSBDAF0QAB0w9GikhqkgBNADABIgABIwAgOdACCjaCIIM
      ---END CERTIFICATE---
      ```
4. In the **Service provider** section, enter the **Entity ID** of your app. This is
   typically your app's URL. On your SAML identity provider, this is
   referred to as the audience.

5. In the **Project settings** side pane, click **Add Domain** , and add your
   app's domain. For example, if your
   app's sign-in URL is `https://example.com/login`, add `example.com`.

6. To complete the setup, do one of the following:

   - Copy the default authorization callback URL from the **Authorization callback (URL)**
     field and add it to your SAML app configuration.

     Using the default authorization callback URL reduces the complexity of
     validating the SAML response.
   - Add your customized authorization callback URL to your SAML app configuration---for example, `https://PROJECT-ID.firebaseapp.com/__/auth/handler`.

7. In the **Configure your application** section, click **Setup Details**.
   Copy the snippet into your app's code to initialize the Identity Platform
   client SDK.

8. Click **Save**.

### Provider required elements

Identity Platform expects the `<saml:Subject>` and `<saml:NameID>` elements in responses from the provider.
If you don't define values for these elements when configuring your provider, the SAML assertion fails.

### Sign requests

You can increase the security of your authentication requests by signing them.

To sign requests, first enable signed requests for your identity provider by
calling [`inboundSamlConfigs.patch()`](https://docs.cloud.google.com/identity-platform/docs/reference/rest/v2/projects.inboundSamlConfigs/patch.md.txt)
and setting `idp_config.sign_request` to `true`:

### REST


Before using any of the request data,
make the following replacements:

- `project-id`: the ID for the Google Cloud project
- `provider-id`: the SAML provider ID


HTTP method and URL:

```
PATCH https://identitytoolkit.googleapis.com/admin/v2/projects/project-id/inboundSamlConfigs/provider-id?updateMask=idpConfig.signRequest
```


Request JSON body:

```
{
  "idp_config": {
    "sign_request": true
  }
}
```

To send your request, expand one of these options:

#### curl (Linux, macOS, or Cloud Shell)

> [!NOTE]
> **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](https://docs.cloud.google.com/sdk/gcloud/reference/init) or [`gcloud auth login`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) , or by using [Cloud Shell](https://docs.cloud.google.com/shell/docs.md.txt), which automatically logs you into the `gcloud` CLI . You can check the currently active account by running [`gcloud auth list`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/list.md.txt).


Save the request body in a file named `request.json`,
and execute the following command:

```
curl -X PATCH \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "x-goog-user-project: project-id" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d @request.json \
     "https://identitytoolkit.googleapis.com/admin/v2/projects/project-id/inboundSamlConfigs/provider-id?updateMask=idpConfig.signRequest"
```

#### PowerShell (Windows)

> [!NOTE]
> **Note:** The following command assumes that you have logged in to the `gcloud` CLI with your user account by running [`gcloud init`](https://docs.cloud.google.com/sdk/gcloud/reference/init) or [`gcloud auth login`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/login.md.txt) . You can check the currently active account by running [`gcloud auth list`](https://docs.cloud.google.com/sdk/gcloud/reference/auth/list.md.txt).


Save the request body in a file named `request.json`,
and execute the following command:

```
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
    -Method PATCH `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://identitytoolkit.googleapis.com/admin/v2/projects/project-id/inboundSamlConfigs/provider-id?updateMask=idpConfig.signRequest" | Select-Object -Expand Content
```

#### APIs Explorer (browser)


Copy the request body and open the

[method reference page](https://docs.cloud.google.com/identity-platform/docs/reference/rest/v2/projects.inboundSamlConfigs/patch.md.txt).
The APIs Explorer panel opens on the right side of the page.
You can interact with this tool to send requests.

Paste the request body in this tool, complete any other required fields, and click **Execute**.

<br />

You must use the REST API to enable signed requests; using the
Google Cloud console or Google Cloud CLI is not supported.

The response is an
[`InboundSamlConfig`](https://docs.cloud.google.com/identity-platform/docs/reference/rest/v2/projects.inboundSamlConfigs.md.txt#spconfig)
object, which includes an array of [`SpCertificate`](https://docs.cloud.google.com/identity-platform/docs/reference/rest/v2/projects.inboundSamlConfigs.md.txt#spcertificate)
objects.
Configure the value of the X509 certificate with your SAML identity provider so
it can validate the signature of your requests.

> [!CAUTION]
> **Caution:** To prevent authentication disruption, monitor the expiration date of your SP certificates and plan certificate rotation in advance during scheduled downtime.

### Rotate service provider certificates

When using signed SAML requests, Identity Platform uses a Service
Provider (SP) certificate. To prevent authentication disruption, monitor the
expiration date of your SP certificates and rotate them before they expire.

> [!CAUTION]
> **Caution:**
>
> - **Irreversible operation:** Rotating the SP certificate is irreversible. You cannot reinstate a previous certificate.
> - **Service disruption:** Updating the SP certificate breaks SSO for all users until the new certificate is updated at your IdP. This rotation must be coordinated in advance across Cloud Customer Care, your organization's team, and IdP administrators.

1. To check SP certificate expiration, extract the certificate expiration
   timestamps using [`jq`](https://jqlang.github.io/jq/):

   ```bash
   curl -s -X GET "https://identitytoolkit.googleapis.com/v2/projects/PROJECT_ID/inboundSamlConfigs" \
       -H "Authorization: Bearer $(gcloud auth print-access-token)" \
       -H "X-Goog-User-Project: PROJECT_ID" \
       -H "Content-Type: application/json" | \
       jq -r '.inboundSamlConfigs[].spConfig.spCertificates[]?.expiresAt'
   ```

   Replace `PROJECT_ID` with your Google Cloud
   project ID.

   Check the `expiresAt` value under `spConfig.spCertificates`.
2. If the expiration timestamp (`expiresAt`) is within 30 days or within the
   timeframe required by your organization, contact
   [Cloud Customer Care](https://cloud.google.com/support) and your IdP administrator
   to plan the update during a scheduled downtime.

3. To rotate the certificate and receive the new public certificate, work with
   Cloud Customer Care.

4. To update the certificate configuration on your IdP, share the new SP
   certificate with your IdP administrator.

5. Test whether single sign-on (SSO) works with the updated
   configuration.

## Sign in users

When you sign a user in, the client SDK handles the authentication
handshake, then returns ID tokens containing the SAML attributes in their
payloads. To sign a user in and get attributes from the SAML provider:

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

   ### Web version 9

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

   const provider = new SAMLAuthProvider("saml.myProvider");
   ```

   ### Web version 8

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

   ### Popup

   ### Web version 9

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

   const auth = getAuth();
   signInWithPopup(auth, provider)
     .then((result) => {
       // User is signed in.
       // Provider data available from the result.user.getIdToken()
       // or from result.user.providerData
     }).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 = SAMLAuthProvider.credentialFromError(error);
       // Handle / display error.
       // ...
     });
   ```

   ### Web version 8

   ```javascript
   firebase.auth().signInWithPopup(provider)
     .then((result) => {
       // User is signed in.
       // Identity provider data available in result.additionalUserInfo.profile,
       // or from the user's ID token obtained from result.user.getIdToken()
       // as an object in the firebase.sign_in_attributes custom claim
       // This is also available from result.user.getIdTokenResult()
       // idTokenResult.claims.firebase.sign_in_attributes.
     })
     .catch((error) => {
       // Handle / display 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);
   ```

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

   ### Web version 9

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

   const auth = getAuth();
   getRedirectResult(auth)
     .then((result) => {
       // User is signed in.
       // Provider data available from the result.user.getIdToken()
       // or from result.user.providerData
     })
     .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 = SAMLAuthProvider.credentialFromError(error);
       // Handle / display error.
       // ...
     });
   ```

   ### Web version 8

   ```javascript
   firebase.auth().getRedirectResult()
     .then((result) => {
       // User is signed in.
       // Provider data available in result.additionalUserInfo.profile,
       // or from the user's ID token obtained from result.user.getIdToken()
       // as an object in the firebase.sign_in_attributes custom claim
       // This is also available from result.user.getIdTokenResult()
       // idTokenResult.claims.firebase.sign_in_attributes.
     }).catch((error) => {
       // Handle / display error.
       // ...
     });
   ```
3. Retrieve the user attributes associated with the SAML provider from the ID
   token using the `firebase.sign_in_attributes` claim. Make sure to verify the
   ID token using the Admin SDK when you send it to your server.

   The ID token includes the user's email address only if it is provided in the
   `NameID` attribute of the SAML assertion from the identity provider:

   ```xml
   <Subject>
     <NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">test@email.com</NameID>
   </Subject>
   ```

   This is populated in the Firebase-issued ID token and in the [UserInfo](https://firebase.google.com/docs/reference/js/auth.userinfo#userinfoemail) object.

Only service-provider initiated SAML flows from the client SDK
are supported.

## Link 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 SAML provider by using `linkWithPopup()` or `linkWithRedirect()`.

The following code snippet shows how to link a user's Google Account to the SAML provider:

### 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 OIDC](https://docs.cloud.google.com/identity-platform/docs/web/oidc.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)