> ## Documentation Index
> Fetch the complete documentation index at: https://auth0.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Describes the special configuration scenario to sign and encrypt SAML requests

# Sign and Encrypt SAML Requests

export const AuthLink = ({href, target = "_blank", rel = "noopener noreferrer", children}) => {
  const [processedHref, setProcessedHref] = useState(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        let processedHref = href;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
          processedHref = processedHref.replace(new RegExp(escapedKey, "g"), value);
        }
        if (processedHref !== href) {
          setProcessedHref(processedHref);
        }
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [href]);
  if (!processedHref) {
    return <code>{href}</code>;
  }
  return <a className="link" href={processedHref} target={target} rel={rel}>
      {children}
    </a>;
};

To increase the security of your transactions, you can sign or encrypt both your requests and your responses in the <Tooltip tip="Security Assertion Markup Language (SAML): Standardized protocol allowing two parties to exchange authentication information without a password." cta="View Glossary" href="/docs/glossary?term=SAML">SAML</Tooltip> protocol. In this article, you'll find configurations for specific scenarios, separated under two use cases:

* Auth0 as the SAML service provider (for example, a SAML connection)
* Auth0 as the SAML <Tooltip tip="Identity Provider (IdP): Service that stores and manages digital identities." cta="View Glossary" href="/docs/glossary?term=identity+provider">identity provider</Tooltip> (for example, an application configured with the SAML Web App addon)

## Auth0 as the SAML service provider

These scenarios apply when Auth0 is the SAML Service Provider, which means that Auth0 connects to a SAML identity provider by creating a SAML connection.

### Sign the SAML authentication request

If Auth0 is the SAML **service provider**, you can sign the authentication request Auth0 sends to the IdP as follows:

1. Navigate to [Auth0 Dashboard > Authentication > Enterprise](https://manage.auth0.com/#/connections/enterprise), and select **SAML**.
2. Select the name of the connection to view.
3. Locate **Sign Request**, and enable its switch.
4. Download the certificate beneath the **Sign Request** switch, and provide it to the IdP so that it can validate the signature.

#### Enable/disable deflate encoding

By default, SAML authentication requests are sent via HTTP-Redirect and use deflate encoding, which puts the signature in a query parameter.

To turn off deflate encoding, you can make a [PATCH call to the Management API's Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) and set the `deflate` option to `false`.

Updating the `options` object for a connection overrides the whole `options` object. To keep previous connection options, get the existing `options` object and add new key/values to it.

Endpoint: `https://{yourDomain}/api/v2/connections/{yourConnectionId}`

Payload:

```json lines theme={null}
{
	{ 
		"options" : {
			[...], // all the other connection options
		  "deflate": false
    }
  }
}
```

### Use a custom key to sign requests

By default, Auth0 uses the tenant private key to sign SAML requests (when the **Sign Request** toggle is enabled). You can also provide your own private/public key pair to sign requests coming from a specific connection.

You can generate your own certificate and private key using this command:

```bash wrap lines theme={null}
openssl req -x509 -nodes -sha256 -days 3650 -newkey rsa:2048 -keyout private_key.key -out certificate.crt
```

Changing the key used to sign requests in the connection can't be done on the Dashboard UI, so you will have to use the [Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) from the <Tooltip tip="Management API: A product to allow customers to perform administrative tasks." cta="View Glossary" href="/docs/glossary?term=Management+API">Management API</Tooltip> v2, and add a `signing_key` property to the `options` object, as shown in the payload example below.

Updating the `options` object for a connection overrides the whole `options` object. To keep previous connection options, get the existing `options` object and add new key/values to it.

Endpoint: `https://{yourDomain}/api/v2/connections/{yourConnectionId}`

Payload:

```json lines theme={null}
{
	{ 
		"options" : {
			[...], // all the other connection options
		  "signing_key": {
				"key":"-----BEGIN PRIVATE KEY-----\n...{your private key here}...\n-----END PRIVATE KEY-----",
				"cert":"-----BEGIN CERTIFICATE-----\n...{your public key cert here}...\n-----END CERTIFICATE-----"
			}
    }
	}
}
```

To learn how to get the private key and certificate formatted as a JSON string to use in the payload, see [Work with Certificates and Keys and Strings](/docs/authenticate/protocols/saml/saml-sso-integrations/work-with-certificates-and-keys-as-strings).

### Receive signed SAML authentication responses

If Auth0 is the SAML **service provider**, all SAML responses from your identity provider should be signed to indicate it hasn't been tampered with by an unauthorized third-party.

You will need to configure Auth0 to validate the responses' signatures by obtaining a signing certificate form the identity provider and loading the certificate from the identity provider into your Auth0 Connection:

1. Navigate to [Auth0 Dashboard > Authentication > Enterprise](https://manage.auth0.com/#/connections/enterprise), and select **SAML**.
2. Select the name of the connection to view.
3. Locate **X509 Signing Certificate**, and upload the certificate.
4. Select **Save Changes**.

Auth0 can accept a signed response for the assertion, the response, or both.

### Receive encrypted SAML authentication assertions

If Auth0 is the SAML service provider, it may need to receive encrypted assertions from an identity provider. To do this, you must provide the tenant's public key certificate to the IdP. The IdP encrypts the SAML assertion using the public key and sends it to Auth0, which decrypts it using the tenant's private key.

Use the following links to obtain the public key in different formats:

* <AuthLink href="https://{yourDomain}/cer?cert=connection">CER</AuthLink>
* <AuthLink href="https://{yourDomain}/pem?cert=connection">PEM</AuthLink>
* <AuthLink href="https://{yourDomain}/rawpem?cert=connection">raw PEM</AuthLink>
* <AuthLink href="https://{yourDomain}/pb7?cert=connection">PKCS#7</AuthLink>
* <AuthLink href="https://{yourDomain}/fingerprint?cert=connection">Fingerprint</AuthLink>

Download the certificate in the format requested by the IdP.

#### Set Content Decryption Algorithms

By default, Auth0 automatically supports the algorithms listed in the latest [Algorithm Profile](/docs/authenticate/protocols/saml/saml-sso-integrations/algorithm-profiles) for decrypting SAML assertions.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  If the assertion is encrypted with an algorithm not in the list, then the assertion will be rejected by Auth0.
</Callout>

To specify a different profile or use an unlisted algorithm, you need to update the connection using the [Update a Connection](https://auth0.com/docs/api/management/v2/connections/patch-connections-by-id) endpoint and change the `assertion_decryption_settings` property as shown in the payload example below.

When you update the options object for a connection, the new configuration overrides the whole `options` object. To keep previous connection options, get the existing options object and add new key/values to it.

Endpoint: `https://{yourDomain}/api/v2/connections/{yourConnectionId}`
Payload:

```json theme={null}
{
  "options": {
    [...], // all the other connection options
    "assertion_decryption_settings": {
      "algorithm_profile": "v2026-1",
      "algorithm_exceptions": []
    }
  }
}
```

### Use your key pair to decrypt encrypted responses

As noted above, Auth0 will by default use your tenant's private/public key pair to handle encryption. You can also provide your own public/private key pair if an advanced scenario requires so.

Changing the key pair used to encrypt and decrypt requests in the connection can't be done on the Dashboard UI, so you will have to use the [Update a Connection endpoint](https://auth0.com/docs/api/management/v2#!/Connections/patch_connections_by_id) from the Management API v2, and add a `decryptionKey` property to the `options` object, as shown in the payload example below.

Updating the `options` object for a connection overrides the whole `options` object. To keep previous connection options, get the existing `options` object and add new key/values to it.

Endpoint: `https://{yourDomain}/api/v2/connections/{yourConnectionId}`

Payload:

```json lines theme={null}
{
	{ 
		"options" : {
			[...], // all the other connection options
		  "decryptionKey": {
				"key":"-----BEGIN PRIVATE KEY-----\n...{your private key here}...\n-----END PRIVATE KEY-----",
				"cert":"-----BEGIN CERTIFICATE-----\n...{your public key cert here}...\n-----END CERTIFICATE-----"
			}
	}
}
```

The SAML metadata available for the connection will be updated with the provided certificate so that the identity provider can pick it up to sign the SAML response.

## Auth0 as the SAML identity provider

This scenario applies when Auth0 is the SAML identity provider for an application. This is represented in the Dashboard by an **Application** that has the SAML Web App Addon enabled.

### Sign the SAML responses/assertions

If Auth0 is the SAML identity provider, it will sign SAML assertions with the tenant's private key and provide the service provider with the public key/certificate necessary to validate the signature.

To sign the SAML assertions:

1. Go to [Auth0 Dashboard > Applications](https://manage.auth0.com/#/applications), and select the name of the application to view.
2. Scroll to the bottom of the **Settings** page, select **Show Advanced Settings**, and select the **Certificates** view.
3. Select **Download Certificate**, and select the format in which you'd like to receive your signing certificate.
4. Send your certificate to the service provider.

By default, Auth0 signs the SAML **assertion** within the response. To sign the SAML **response** instead:

1. Navigate to [Auth0 Dashboard > Applications](https://manage.auth0.com/#/applications), and select the name of the application to view.
2. Select the **Addons** view.
3. Select **SAML2 Web App** to view its settings, and locate the **Settings** code block.
4. Locate the **`"signResponse"`** key. Uncomment it (or add it, if required), then set its value to `true` (the default value is `false`). The configuration should look like this:

   ```json lines theme={null}
   {
     [...], // other settings
     "signResponse": true
   }
   ```

#### Change the signing key for SAML responses

By default, Auth0 will use the private/public key pair assigned to your tenant to sign SAML responses or assertions. For very specific scenarios, you might wish to provide your own key pair. You can do so with a rule like this:

```javascript lines expandable theme={null}
/**
* Handler that will be called during the execution of a PostLogin flow.
*
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {

    // replace with the ID of the application that has the SAML Web App Addon enabled
      // for which you want to change the signing key pair.
      const samlIdpClientId = 'YOUR_SAML_APP_CLIENT_ID';

    // only do this for the specific client ID.  If you have multiple IdPs that require 
    // custom certificates, you will have an "if" statement for each one.  
    if (event.client.client_id === samlIdpClientId) {

    // provide your own private key and certificate here  
    // see https://auth0.com/docs/authenticate/protocols/saml/saml-sso-integrations/work-with-certificates-and-keys-as-strings 
    // for formatting instructions basically you start with a PEM format certificate and
    // replace the line enedings with "\n"
    const signingCert = "-----BEGIN CERTIFICATE-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV[..all the other lines..]-----END CERTIFICATE-----\n";
    const signingKey = "-----BEGIN PRIVATE KEY-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV[..all the other lines..]-----END PRIVATE KEY-----\n";

    api.samlResponse.setCert(signingCert)    
    api.samlResponse.setKey(signingKey);

  }
  };
```

To learn how to turn the private key and certificate files into strings that you can use in a rule, see [Work with Certificates and Keys and Strings](/docs/authenticate/protocols/saml/saml-sso-integrations/work-with-certificates-and-keys-as-strings).

### Receive signed SAML authentication requests

If Auth0 is the SAML identity provider, it can receive requests signed with the service provider's private key. Auth0 uses the public key/certificate to validate the signature.

To configure signature validation:

1. Download the service provider's certificate with the public key.
2. Navigate to [Auth0 Dashboard > Applications](https://manage.auth0.com/#/applications), and select the name of the application to view.
3. Select the **Addons** view.
4. Select **SAML2 Web App** to view its settings, and locate the **Settings** code block.
5. Locate the **`"signingCert"`** key. Uncomment it (or add it, if required), then set its value to the certificate you downloaded from the service provider. The configuration should look like this:

   ```json lines theme={null}
   {
     [...], // other settings
     "signingCert": "-----BEGIN CERTIFICATE-----\nMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n[..all the other lines..]-----END CERTIFICATE-----\n"
   }
   ```

### Send encrypted SAML authentication assertions

If Auth0 is the SAML identity provider, you can use [Actions](/docs/customize/actions) to encrypt the SAML assertions it sends. You can also select the encryption algorithm used for assertion encryption. Auth0 recommends using `aes256-gcm` for a stronger security posture.

You must obtain the certificate and the public key from the service provider. If you only got the certificate, you can derive the public key using `openssl`. Assuming that the certificate file is named `certificate.pem`, you can run:

`openssl x509 -in certificate.pem -pubkey -noout > public_key.pem`

Once you get the certificate and public key files, you must [turn them into strings](/docs/authenticate/protocols/saml/saml-sso-integrations/work-with-certificates-and-keys-as-strings) to use them in an Action. The Action will look like this:

```js lines theme={null}
exports.onExecutePostLogin = async (event, api) => {

// this Action sets a specific public key to encrypt the SAML assertion generated from Auth0
  if (
    event.client.client_id ===
    "THE_CLIENT_ID_OF_THE_APP_WITH_THE_SAML_APP_ADDON"
  ) {
    const encryptionCert =
      "-----BEGIN CERTIFICATE-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV[..all the other lines..]-----END CERTIFICATE-----\n";
    const encryptionPublicKey =
      "-----BEGIN PUBLIC KEY-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV[..all the other lines..]-----END PUBLIC KEY-----\n";

    api.samlResponse.setEncryptionCert(encryptionCert);
    api.samlResponse.setEncryptionPublicKey(encryptionPublicKey);
    api.samlResponse.setEncryptionAlgorithm("aes256-gcm");
  }
};
```

Auth0 supports the following algorithms for assertion encryption:

* [`aes256-gcm`](https://www.w3.org/TR/xmlenc-core1/#sec-AES-GCM) **(recommended)**: Authenticated encryption that provides both confidentiality and integrity. It is resistant to format validity oracle attacks.
* [`aes256-cbc`](https://www.w3.org/TR/xmlenc-core1/#sec-AES) (default): It does not provide integrity guarantees. When an Action does not use the object [`api.samlResponse.setEncryptionAlgorithm`](/docs/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-api-object#api-samlresponse-setencryptioncert-encryptioncert) to set the encryption algorithm, Auth0 defaults to the `aes256-cbc` algorithm and logs a deprecation warning in your tenant logs.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  For key transport, Auth0 uses [`rsa-oaep`](https://www.w3.org/TR/xmlenc-core1/#rsa-oaep) including MGF1 and SHA1 functions.
</Callout>

<Warning>
  Auth0 intends to update the default encryption algorithm to `aes256-gcm`.

  For consistent behavior after the default algorithm changes, we recommend switching to `aes256-gcm`:

  1. Verify that your SAML service provider supports `aes256-gcm`, and contact them for support if they do not.
  2. Set the encryption algorithm in your Action code with `api.samlResponse.setEncryptionAlgorithm("aes256-gcm");`.
</Warning>

## Learn more

* [Work with Certificates and Keys as Strings](/docs/authenticate/protocols/saml/saml-sso-integrations/work-with-certificates-and-keys-as-strings)
