[Yandex Cloud documentation](../../../index.md) > [Yandex Identity Hub](../../index.md) > [Tutorials](../index.md) > [Managing identity federations](index.md) > Keycloak authentication

# Keycloak authentication

With an [identity federation](../../concepts/add-federation.md), you can use [Keycloak](https://www.keycloak.org/) to authenticate users in an organization.

Authentication setup includes the following steps:

1. [Creating and setting up a federation in Yandex Identity Hub](#yc-settings).

1. [Creating and setting up a SAML application in Keycloak](#keycloak-settings).

1. [Adding users to Yandex Identity Hub](#add-users).

1. [Authentication](#test-auth).

## Getting started {#before-you-begin}

To follow the steps in this section, you will need:​

1. Docker. If you do not have Docker yet, [install it](https://docs.docker.com/get-docker/). Make sure Docker Engine is running.

1. [Keycloak](https://www.keycloak.org/) local IdP server. To install and start Keycloak, run these commands:

    {% list tabs %}

    - Keycloak 20 in developer mode

      ```bash
      docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=Pa55w0rd quay.io/keycloak/keycloak:latest start-dev
      ```

    - Keycloak 19

      ```bash
      git clone https://github.com/keycloak/keycloak-containers.git
      cd ./keycloak-containers/docker-compose-examples
      docker-compose -f keycloak-postgres.yml up
      ```

    {% endlist %}

    {% note info %}

    To enable employees on a corporate network or the internet to use Keycloak for authentication in your application, deploy the Keycloak IdP server on the network and set up a public address. Read more in the [Keycloak documentation](https://www.keycloak.org/server/hostname).

    {% endnote %}

1. Valid certificate used for signing in the Keycloak service. To get it: 

    1. Log in to the Keycloak administrator account at:

        {% list tabs %}

        - Keycloak 17 or higher

          `http://keycloak.example.com:8080/admin`. Replace `keycloak.example.com` with your local server address, e.g., `http://localhost:8080/admin`.

        - Keycloak 16 or lower

          `http://keycloak.example.com:8080/auth/admin`. Replace `keycloak.example.com` with your local server address, e.g., `http://localhost:8080/auth/admin`.

        {% endlist %}

        The default login credentials are as follows:
        * **User name or email**: `admin`.
        * **Password**: `Pa55w0rd`.

    1. In the **Realm Settings** section, select the **Keys** tab.

    1. In the **RS256** line, click **Certificate** and copy the certificate value.

    1. Save the certificate as a text file with the `.cer` extension in the following format:

        ```
        -----BEGIN CERTIFICATE-----
          <certificate_value>
        -----END CERTIFICATE-----
        ```

    You can also get the certificate through this direct link:

    {% list tabs %}

    - Keycloak 17 or higher

      `http://keycloak.example.com:8080/realms/master/protocol/saml/descriptor`. The certificate value is stored in the `<ds:X509Certificate>...</ds:X509Certificate>` tag.

    - Keycloak 16 or lower

      `http://keycloak.example.com:8080/auth/realms/master/protocol/saml/descriptor`. The certificate value is stored in the `<ds:X509Certificate>...</ds:X509Certificate>` tag.

    {% endlist %}

## Creating and setting up a federation in Yandex Identity Hub {#yc-settings}

### Create a federation {#create-federation}

{% list tabs group=instructions %}

- Cloud Center UI {#cloud-center}

  1. Go to [Yandex Identity Hub](https://center.yandex.cloud/organization).

  1. In the left-hand panel, select ![icon-federation](../../../_assets/console-icons/vector-square.svg) **Federations**.

  1. Click ![Circles3Plus](../../../_assets/console-icons/circles-3-plus.svg) **Create federation** in the top-right corner of the page. In the window that opens:

      1. Give your federation a name. It must be unique within the folder.

      1. You can also add a description, if required.

      1. In the **Cookie lifetime** field, specify the time before the browser asks the user to re-authenticate.

      1. In the **IdP Issuer** field, enter a link in this format:

          - Keycloak 17 or higher

              ```
              http://<host>:8080/realms/master
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. Here is an example:

              ```
              http://keycloak.example.com:8080/realms/master
              ```

          - Keycloak 16 or lower

              ```
              http://<host>:8080/auth/realms/master
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

              ```
              http://keycloak.example.com:8080/auth/realms/master
              ```

      1. In the **Link to the IdP login page** field, enter a link in this format:

          - Keycloak 17 or higher

              ```
              http://<host>:8080/realms/master/protocol/saml
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

              ```
              http://keycloak.example.com:8080/realms/master/protocol/saml
              ```

          - Keycloak 16 or lower

              ```
              http://<host>:8080/auth/realms/master/protocol/saml
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

              ```
              http://keycloak.example.com:8080/auth/realms/master/protocol/saml
              ```

          You can only use HTTP and HTTPS in a link.

      1. Enable **Automatically create users** to automatically add a new user to your organization after authentication. Otherwise, you will need to [manually add](../../operations/add-account.md#add-user-sso) your federated users.

          A federated user is created automatically only when they log in to a cloud for the first time. If you removed a user from the federation, you can only add them back manually.

      1. To make sure all authentication requests from Yandex Cloud contain a digital signature, enable the **Sign authentication requests** option. To complete the configuration, download and [install](#signature) a Yandex Cloud certificate.
      
          In the **SAML certificates** block that appears, you will see the information about the current Yandex Cloud SAML certificate.
          
          Click ![ArrowDownToLine](../../../_assets/console-icons/arrow-down-to-line.svg) **Download** and save the downloaded certificate file. You will need to upload it to you IdP server.
          
          {% note tip %}
          
          Track certificate expiration dates and always install a new certificate before the current one expires. Make sure to [download the re-issued Yandex Cloud SAML certificate and install](../../operations/renew-yc-certificate.md) it on the IdP provider's side and in your federation well in advance.
          
          {% endnote %}
      
          You can also download a certificate after creating a federation. To do this, click ![ArrowDownToLine](../../../_assets/console-icons/arrow-down-to-line.svg) **Download certificate** in the **Sign authentication requests** field on the Yandex Identity Hub federation info page.

      1. Enable **Mandatory re-authentication (ForceAuthn) in IdP** to set [ForceAuthn](../../saml/api-ref/Federation/index.md) to `true` in the SAML authentication request. If enabled, the IdP will request the user to re-authenticate once the Yandex Cloud session expires. This is an optional parameter.

      1. Click **Create federation**.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

  1. View the description of the create federation command:

     ```bash
     yc organization-manager federation saml create --help
     ```

  1. Create a federation:

      - Keycloak 17 or higher

        ```bash
        yc organization-manager federation saml create --name my-federation \
          --organization-id <organization_ID> \
          --auto-create-account-on-login \
          --encrypted-assertions \
          --cookie-max-age 12h \
          --issuer "http://<host>:8080/realms/master" \
          --sso-binding POST \
          --sso-url "http://<host>:8080/realms/master/protocol/saml" \
          --force-authn
        ```

      - Keycloak 16 or lower

        ```bash
        yc organization-manager federation saml create --name my-federation \
          --organization-id <organization_ID> \
          --auto-create-account-on-login \
          --encrypted-assertions \
          --cookie-max-age 12h \
          --issuer "http://<host>:8080/auth/realms/master" \
          --sso-url "http://<host>:8080/auth/realms/master/protocol/saml" \
          --sso-binding POST \
          --force-authn
        ```

        Where:

        * `--name`: Federation name. It must be unique within the folder.

        * `--organization-id`: [Organization ID](../../operations/organization-get-id.md).

        * `--auto-create-account-on-login`: Flag enabling the automatic creation of new cloud users after authenticating on the IdP server.
        This option makes it easier to create users; however, users created this way will not be able to do anything with cloud resources. This does not apply to the resources for which roles are assigned to the `All users` or `All authenticated users` [public group](../../../iam/concepts/access-control/public-group.md).

          If this option is off, users not added to the organization will not be able to log in to the management console, even if authenticated on your IdP server. In this case, you can manage a list of users allowed to use Yandex Cloud resources.

        * `--encrypted-assertions`: Flag enabling a digital signature for authentication requests. To complete the configuration, download and [install](#signature) a Yandex Cloud certificate.

        * `--cookie-max-age`: Time before the browser asks the user to re-authenticate.

        * `--issuer`: ID of the IdP server to use for authentication:

          - Keycloak 17 or higher

            ```
            http://<host>:8080/realms/master
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. Here is an example:

            ```
            http://keycloak.example.com:8080/realms/master
            ```

          - Keycloak 16 or lower

            ```
            http://<host>:8080/auth/realms/master
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

            ```
            http://keycloak.example.com:8080/auth/realms/master
            ```

        * `--sso-url`: URL of the page the browser has to redirect the user to for authentication:

            - Keycloak 17 or higher

              ```
              http://<host>:8080/realms/master/protocol/saml
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

              ```
              http://keycloak.example.com:8080/realms/master/protocol/saml
              ```

            - Keycloak 16 or lower

              ```
              http://<host>:8080/auth/realms/master/protocol/saml
              ```

              If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

              ```
              http://keycloak.example.com:8080/auth/realms/master/protocol/saml
              ```

            You can only use HTTP and HTTPS in a link.

        * `--sso-binding`: Specify the single sign-on binding type. Most identity providers support the `POST` binding type.

        * `--force-authn`: Once the Yandex Cloud session expires, your IdP will prompt the user to re-authenticate. This is an optional parameter.

- API {#api}

  1. Create a request body file, e.g., `body.json`:

      - Keycloak 17 or higher

        ```json
        {
          "name": "my-federation",
          "organizationId": "<organization_ID>",
          "autoCreateAccountOnLogin": true,
          "cookieMaxAge":"43200s",
          "issuer": "http://<host>:8080/realms/master",
          "ssoUrl": "http://<host>:8080/realms/master/protocol/saml",
          "securitySettings": {
              "encryptedAssertions": true,
              "forceAuthn": true
          },
          "ssoBinding": "POST"
        }       
        ```

      - Keycloak 16 or lower

        ```json
        {
          "name": "my-federation",
          "organizationId": "<organization_ID>",
          "autoCreateAccountOnLogin": true,
          "cookieMaxAge":"43200s",
          "issuer": "http://<host>:8080/auth/realms/master",
          "ssoUrl": "http://<host>:8080/auth/realms/master/protocol/saml",
          "securitySettings": {
            "encryptedAssertions": true,
            "forceAuthn": true
          },
          "ssoBinding": "POST"
        }       
        ```

        Where:

        * `name`: Federation name. It must be unique within the folder.

        * `organizationId`: [Organization ID](../../operations/organization-get-id.md). 

        * `autoCreateAccountOnLogin`: Flag enabling the automatic creation of new cloud users after authenticating on the IdP server.
        This option makes it easier to create users; however, users created this way will not be able to do anything with cloud resources. This does not apply to the resources for which roles are assigned to the `All users` or `All authenticated users` [public group](../../../iam/concepts/access-control/public-group.md).

          If this option is off, users not added to the organization will not be able to log in to the management console, even if authenticated on your IdP server. In this case, you can manage a list of users allowed to use Yandex Cloud resources.

        * `cookieMaxAge`: Time before the browser asks the user to re-authenticate.

        * `issuer`: ID of the IdP server to use for authentication:

          - Keycloak 17 or higher

            ```
            http://<host>:8080/realms/master
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. Here is an example:

            ```
            http://keycloak.example.com:8080/realms/master
            ```

          - Keycloak 16 or lower

            ```
            http://<host>:8080/auth/realms/master
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. 

            For example:

            ```
            http://keycloak.example.com:8080/auth/realms/master
            ```

        * `ssoUrl`: URL of the page the browser has to redirect the user to for authentication:

          - Keycloak 17 or higher

            ```
            http://<host>:8080/realms/master/protocol/saml
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

            ```
            http://keycloak.example.com:8080/realms/master/protocol/saml
            ```

          - Keycloak 16 or lower

            ```
            http://<host>:8080/auth/realms/master/protocol/saml
            ```

            If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. For example:

            ```
            http://keycloak.example.com:8080/auth/realms/master/protocol/saml
            ```

          You can only use HTTP and HTTPS in a link.

        * `encryptedAssertions`: Flag enabling a digital signature for authentication requests. To complete the configuration, download and [install](#signature) a Yandex Cloud certificate.

        * `forceAuthn`: Parameter that requires the user to re-authenticate once their Yandex Cloud session expires. This is an optional parameter.

        * `ssoBinding`: Specify the single sign-on binding type. Most identity providers support the `POST` binding type.

  1. To create a federation, use the [create](../../saml/api-ref/Federation/create.md) REST API method for the [Federation](../../saml/api-ref/Federation/index.md) resource or the [FederationService/Create](../../saml/api-ref/grpc/Federation/create.md) gRPC API call and provide a file with the query parameters in your query.
     
     Query example:
     
     ```bash
     curl \
       --request POST \
       --header "Content-Type: application/json" \
       --header "Authorization: Bearer <IAM_token>" \
       --data '@body.json' \
       https://organization-manager.api.cloud.yandex.net/organization-manager/v1/saml/federations
     ```
     
     Response example:
     
     ```bash
     {
      "done": true,
      "metadata": {
       "@type": "type.googleapis.com/yandex.cloud.organization-manager.v1.saml.CreateFederationMetadata",
       "federationId": "ajeobmje4dgj********"
      }
     ```
     
     The `federationId` property contains the ID of the federation you created. Save it for later use.

- Terraform {#tf}

  If you do not have Terraform yet, [install it and configure the Yandex Cloud provider](../../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
  
  
  To manage infrastructure using Terraform under a service account or user accounts (a Yandex account, a federated account, or a local user), [authenticate](../../../terraform/authentication.md) using the appropriate method.

  1. Describe the federation parameters in the configuration file.

      Here is an example of the configuration file structure:

      - Keycloak 17 or higher

          ```hcl
          resource "yandex_organizationmanager_saml_federation" federation {
          name            = "my-federation"
          organization_id = "<organization_ID>"
          auto_create_account_on_login = "true"
          issuer          = "http://<host>:8080/realms/master"
          sso_url         = "http://<host>:8080/realms/master/protocol/saml"
          sso_binding     = "POST"
          security_settings {
              encrypted_assertions = "true"
              force_authn          = "true"
            }
          }
          ```

      - Keycloak 16 or lower

          ```hcl
          resource "yandex_organizationmanager_saml_federation" federation {
          name            = "my-federation"
          organization_id = "<organization_ID>"
          auto_create_account_on_login = "true"
          issuer          = "http://<host>:8080/auth/realms/master"
          sso_url         = "http://<host>:8080/auth/realms/master/protocol/saml"
          sso_binding     = "POST"
          security_settings {
              encrypted_assertions = "true"
              force_authn          = "true"
            }
          }
          ```

      Where:

      * `name`: Federation name. It must be unique within the folder.
      * `description`: Federation description.
      * `organization_id`: [Organization ID](../../operations/organization-get-id.md).
      * `labels`: Set of key/value label pairs assigned to the federation. This is an optional setting.
      * `issuer`: ID of the IdP server to use for authentication: 

        - Keycloak 17 or higher

          ```
          http://<host>:8080/realms/master
          ```

          If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its ID. For example:

          ```
          http://keycloak.example.com:8080/realms/master
          ```

        - Keycloak 16 or lower

          ```
          http://<host>:8080/auth/realms/master
          ```

          If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its ID. For example:

          ```
          http://keycloak.example.com:8080/auth/realms/master
          ``` 

      * `sso_binding`: Specify the single sign-on binding type. Most identity providers support the `POST` binding type.
      * `sso_url`: URL of the page the browser has to redirect the user to for authentication: 

        - Keycloak 17 or higher

          ```
          http://<host>:8080/realms/master/protocol/saml
          ```

          If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. 

          For example:

          ```
          http://keycloak.example.com:8080/realms/master/protocol/saml
          ```

        - Keycloak 16 or lower

          ```
          http://<host>:8080/auth/realms/master/protocol/saml
          ```

          If you set up a [public address](https://www.keycloak.org/server/hostname) for the IdP server, specify its URL. 

          For example:

          ```
          http://keycloak.example.com:8080/auth/realms/master/protocol/saml
          ```

        You can only use HTTP and HTTPS in a link.

      * `cookie_max_age`: Time in seconds before the browser asks the user to re-authenticate. The default value is `8 hours`. 
      * `auto_create_account_on_login`: Flag enabling the automatic creation of new cloud users after authenticating on the IdP server. 
        This option makes it easier to create users; however, users created this way will not be able to do anything with cloud resources. This does not apply to the resources for which roles are assigned to the `All users` or `All authenticated users` [public group](../../../iam/concepts/access-control/public-group.md).

        If this option is off, users not added to the organization will not be able to log in to the management console, even if authenticated on your server. In this case, you can manage a list of users allowed to use Yandex Cloud resources.
      * `case_insensitive_name_ids`: Toggles username case sensitivity.
        If this option is enabled, the IDs of federated user names will be case-insensitive.
      * `security_settings`: Federation security settings:

        * `encrypted_assertions`: Sign authentication requests.
          
          If this option is enabled, all authentication requests from Yandex Cloud will have a digital signature.

        * `force-authn`: Once the Yandex Cloud session expires, your IdP will prompt the user to re-authenticate. This is an optional parameter.

      For more on the properties of the `yandex_organizationmanager_saml_federation` resource, see [this provider guide](../../../terraform/resources/organizationmanager_saml_federation.md).

  1. Make sure the configuration files are correct.

      1. In the terminal, navigate to the directory where you created your configuration file.
      1. Run a check using this command:

          ```bash
          terraform plan
          ```

          If the configuration is described correctly, the terminal displays the federation parameters. Otherwise, Terraform will show any detected errors. 

  1. Create a federation.

      1. If the configuration is correct, run this command:

          ```bash
          terraform apply
          ```

      1. Confirm you want to create a federation.

  This will create a federation in the specified organization. You can check the new federation and its settings in the organization's [Federations](https://org.yandex.cloud/federations) section.

{% endlist %}

### Add certificates {#add-certificate}

While authenticating, the Yandex Identity Hub service should be able to verify the IdP server certificate. To enable this, add the certificate to the federation:

{% list tabs group=instructions %}

- Cloud Center UI {#cloud-center}

  1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
  
  1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
  
  1. Click the row with the federation you want to add a certificate to.
  
  1. Click **Adding a certificate** under **Certificates** at the bottom of the page.
  
  1. Enter certificate name and description.
  
  1. Choose how to add a certificate:
  
      * To add a certificate as a file, click **Choose a file** and specify the path to it.
      * To paste the contents of a copied certificate, select the **Text** method and paste the contents.
  
  1. Click **Add**.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

  1. View the description of the add certificate command:

     ```bash
     yc organization-manager federation saml certificate create --help
     ```

  1. Add a federation certificate by specifying the certificate file path:

     ```bash
     yc organization-manager federation saml certificate create \
       --federation-id <federation_ID> \
       --name "my-certificate" \
       --certificate-file certificate.cer
     ```

- API {#api}

  Use the [create](../../saml/api-ref/Certificate/create.md) method for the [Certificate](../../saml/api-ref/Certificate/index.md) resource:
  1. Create a request body. In the `data` property, specify the contents of the certificate:

     ```json
     {
       "federationId": "<federation_ID>",
       "name": "my-certificate",
       "data": "-----BEGIN CERTIFICATE..."
     }
     ```

  1. Send the request to add the certificate:

     ```bash
     export IAM_TOKEN=CggaAT********
     curl \
       --request POST \
       --header "Content-Type: application/json" \
       --header "Authorization: Bearer ${IAM_TOKEN}" \
       --data '@body.json' \
       "https://organization-manager.api.cloud.yandex.net/organization-manager/v1/saml/certificates"
     ```

{% endlist %}

{% note tip %}

Make sure to reissue certificates and add them to a federation in a timely manner.

To keep track of when your certificate expires, [subscribe](../../operations/subscribe-user-for-notifications.md) to notifications from the organization. Subscribed users get notifications 60, 30, and 5 days before the certificate expires and after its expiration.

{% endnote %}

## Creating and setting up a SAML application in Keycloak {#keycloak-settings}

A SAML application in Keycloak acts as an identity provider (IdP). To create and set up a SAML application:

1. Log in to the Keycloak administrator account at:

   {% list tabs %}

   - Keycloak 17 or higher

     `http://keycloak.example.com:8080/admin`. Replace `keycloak.example.com` with your local server address, e.g., `http://localhost:8080/admin`.

   - Keycloak 16 or lower

     `http://keycloak.example.com:8080/auth/admin`. Replace `keycloak.example.com` with your local server address, e.g., `http://localhost:8080/auth/admin`.

   {% endlist %}

   The default login credentials are as follows:
    * **User name or email**: `admin`.
    * **Password**: `Pa55w0rd`.

1. Create a SAML application:

    {% list tabs %}

    - Keycloak 19 or higher

      1. In the left-hand panel, select **Clients**. Click **Create client**.

      1. In the **Client ID** field, enter the ACS URL to redirect users to after successful authentication.
      
         {% cut "How to get a federation ID" %}
      
         1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
         1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
         1. Select the required federation and copy the **Identifier** field value on the federation info page.
      
         {% endcut %}

         
         {% cut "How to get the federation ACS URL" %}

         1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
         
         1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
         
         1. Select the required federation and copy the **ACS URL** field value on the federation info page.

         {% endcut %}


      1. In the **Client type** field, select **saml**.

      1. Click **Save**.

    - Keycloak 18 or lower

      1. In the left-hand panel, select **Clients**. Click **Create**.

      1. In the **Client ID** field, enter the ACS URL to redirect users to after successful authentication.

         {% cut "How to get a federation ID" %}

         1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
         1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
         1. Select the required federation and copy the **Identifier** field value on the federation info page.

         {% endcut %}

         
         {% cut "How to get the federation ACS URL" %}

         1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
         
         1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
         
         1. Select the required federation and copy the **ACS URL** field value on the federation info page.

         {% endcut %}


      1. In the **Client Protocol** field, select **saml**.

      1. Click **Save**.

    {% endlist %}

1. Set up the SAML application parameters in the **Settings** tab:

    1. Specify the ACS redirect URL, in the following fields:

       {% list tabs %}

       - Keycloak 19 or higher

         * **Home URL**
         * **Valid Redirect URIs**
         * **IDP Initiated SSO Relay State**

       - Keycloak 18 or lower

         * **Valid Redirect URIs**
         * **Base URL**
         * **IDP Initiated SSO Relay State**

       {% endlist %}

       
       {% cut "How to get the federation ACS URL" %}

       1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
       
       1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
       
       1. Select the required federation and copy the **ACS URL** field value on the federation info page.

       {% endcut %}


    1. Enable the following options:
       * **Include AuthnStatement**
       * **Sign Assertions**
       * **Force POST Binding**
       * **Front Channel Logout**

    1. In the **Signature Algorithm** field, select **RSA_SHA256**.

    1. In the **SAML Signature Key Name** field, select **CERT_SUBJECT**.

    1. Select the format you need from the list in the **Name ID Format** field. To make sure this format is provided regardless of the Yandex Identity Hub settings, enable the **Force Name ID format** option.

    1. Click **Save**.

1. If you enabled **Sign authentication requests** when [creating the federation](#create-federation) in Yandex Identity Hub, set up digital signature verification in the SAML application:

    {% list tabs %}

    - Keycloak 19 or higher

      1. In the SAML application **Keys** tab, enable **Encrypt Assertions** and disable **Client Signature Required**.

      1. In the **Select method** field, select **Import**.

      1. In the **Archive Format** field, select **Certificate PEM**. If there is no **Certificate PEM** item, close the window, click **Regenerate** → **Yes** → **Import key**. The item will appear in the list.
      {#signature}
      1. Click **Browse** and select the Yandex Cloud SAML certificate you downloaded earlier to sign authentication requests. If you did not download a SAML certificate when creating the federation, you can download it on the Yandex Identity Hub federation info page by clicking ![ArrowDownToLine](../../../_assets/console-icons/arrow-down-to-line.svg) **Download certificate** in the **Sign authentication requests** field.

      1. Click **Confirm**.

    - Keycloak 18 or lower

      1. In the SAML application settings, select **Encrypt Assertions** and **Client Signature Required** and save the application to update the available tabs.

      1. In the SAML application's **Keys** tab, locate the **Signing Key** and **Encryption Key** sections and click **Import**.

      1. In the **Archive Format** field, select **Certificate PEM**.
      {#signature}
      1. Click **Select file** and select the Yandex Cloud SAML certificate you downloaded earlier to sign authentication requests. If you did not download a SAML certificate when creating the federation, you can download it on the Yandex Identity Hub federation info page by clicking ![ArrowDownToLine](../../../_assets/console-icons/arrow-down-to-line.svg) **Download certificate** in the **Sign authentication requests** field.

      1. Click **Import**.

    {% endlist %}

1. Add users:

    1. In the left-hand panel, select **Users**.

    1. Click **Add user** and specify user data.

    1. Click **Save**.

    1. In the **Credentials** tab, click **Set Password** and enter a password.

## Adding users to Yandex Identity Hub {#add-users}

If you did not enable the **Automatically create users** option when [creating the federation](#yc-settings), you will have to add federated users to your organization manually.

To do this, you will need user name IDs. They are returned by the IdP server together with a response confirming successful authentication.

If the **Automatically create users** option is enabled, a federation will only add users logging in to a cloud for the first time. If a federated user has been deleted, they can only be added again manually.

A user can be added by the organization administrator (the `organization-manager.admin` role) or owner (the `organization-manager.organizations.owner` role). To learn how to grant a role to a user, see [Roles](../../security/index.md#add-role).

{% note info %}

To enable a user to access the [management console](https://console.yandex.cloud), assign them a role for the [cloud](../../security/index.md#access-binding-cloud). For added security, you can assign one of the least priveleged roles, such as `resource-manager.clouds.member`. However, you may also assign other roles if you know which permissions you want to grant to the invited users.

To grant these permissions to all the organization users at once, assign the role to the `All users in organization X` [system group](../../../iam/concepts/access-control/system-group.md#allOrganizationUsers). When using the CLI, API, or Terraform, no additional roles are required.

{% endnote %}

{% list tabs group=instructions %}

- Cloud Center UI {#cloud-center}

  1. Go to [Yandex Identity Hub](https://center.yandex.cloud/organization).
  
  1. In the left-hand panel, select ![icon-users](../../../_assets/console-icons/person.svg) **Users**.
  
  1. In the top-right corner, click ![person-plus](../../../_assets/console-icons/person-plus.svg) **Add user** and select ![key](../../../_assets/console-icons/key.svg) **Add federated users** from the drop-down list.
  
  1. In the **Federation** field, select the identity federation you want to add users from.
  
  1. In the **Users** field, list the name IDs of users, separating them with spaces or line breaks.
  
  1. Click **Add**. This will give the users access to the organization.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

  1. View the description of the add user command:

     ```bash
     yc organization-manager federation saml add-user-accounts --help
     ```

  1. Add users by listing their name IDs separated by a comma:

     ```bash
     yc organization-manager federation saml add-user-accounts --id <federation_ID> \
       --name-ids=alice@example.com,bob@example.com,charlie@example.com
     ```

     Where:

     * `--id`: Federation ID.
     * `--name-ids`: Name IDs of users.

- API {#api}

  To add identity federation users to the cloud:

  1. Create a file with the request body, e.g., `body.json`. In the request body, specify the array of name IDs of users you want to add:

      ```json
      {
        "nameIds": [
          "alice@example.com",
          "bob@example.com",
          "charlie@example.com"
        ]
      }
      ```

  1. Send the request by specifying the federation ID in the parameters:

      ```bash
      curl \
        --request POST \
        --header "Content-Type: application/json" \
        --header "Authorization: Bearer <IAM_token>" \
        --data '@body.json' \
        https://organization-manager.api.cloud.yandex.net/organization-manager/v1/saml/federations/<federation_ID>:addUserAccounts
      ```

{% endlist %}

### Setting up user attribute mappings {#claims-mapping}

Following user authentication, the IdP server will send the user a SAML message via the browser containing:

* Information about successful authentication.

* User attributes such as a list of roles, the user's full name, and email address.

You can set up a mapping between the SAML message attributes and the personal data stored on the IdP server. Follow these steps:

1. Enable the option for mapping the identity provider roles and Yandex Identity Hub:

    1. In the left-hand panel, select **Client Scopes** → **role_list**.

    1. Go to the **Mappers** tab and select **role list**.

    1. Enable the **Single Role Attribute** option.

1. Set up the attributes to provide to Yandex Cloud:

    {% list tabs %}

    - Keycloak 19 or higher

      1. In the left-hand panel, select **Client**, open your SAML application settings, and go to **role_list**.

      1. In the **Client Scopes** tab, select **optional** next to **role_list** and click the line with the same name as your client.

      1. In the window that opens, click **Add predefined mappers**.

      1. Select the attributes you need in the list and click **Add**. The following user attributes are available in Keycloak by default:
          * `X500 email`: Email address.
          * `X500 surname`: Last name.
          * `X500 givenName`: First name.
          * `role list`: List of roles.

      1. You can create additional user attributes such as a phone number. To do this, click **Add mappers** -> **By configuration** -> **User Property**, select **User Attribute** in the **Configure a new mapper** table, and set attribute parameters.

      1. Sync Keycloak attributes and Yandex Identity Hub: open an attribute and edit the **SAML Attribute Name** value. You can find the **SAML Attribute Name** values supported in Yandex Identity Hub below.

    - Keycloak 18 or lower

      1. In the left-hand panel, select **Clients** and open your SAML application's settings.

      1. In the **Mappers** tab, click **Add Builtins**.

      1. Select the desired attributes in the list and click **Add selected**. The following user attributes are available in Keycloak by default:
          * `X500 email`: Email address.
          * `X500 surname`: Last name.
          * `X500 givenName`: First name.
          * `role list`: List of roles.

      1. You can create additional user attributes such as a phone number. To do this, click **Create**, select **User Attribute** in the **Mapper Type** field, and set attribute parameters.

      1. Sync Keycloak attributes and Yandex Identity Hub: open an attribute and edit the **SAML Attribute Name** value. You can find the **SAML Attribute Name** values supported in Yandex Identity Hub below.

   {% endlist %}

1. If you created additional attributes, add them to user parameters:

    1. In the left-hand panel, select **Users**, open the user parameters, and go to the **Attributes** tab.

    1. In the **Key** field, enter the **Name** given to the additional attribute.

    1. In the **Value** field, enter the user data to include in the attribute.

        {% note info %}

        By default, the **Value** field is limited to 256 characters. Attributes may contain more characters, for example, a Base64-encoded profile image. To add such a value, change the field data type in the `user_attribute` table in the internal Keycloak storage. 

        {% endnote %}

    1. Click **Add** and then click **Save**.

User data | Comment | SAML Attribute Name
------------------- | ----------- | -------------------
Surname | Used for search in Yandex Cloud services.<br> Value length limit: 64 characters. | `lastName`
Name | Used for search in Yandex Cloud services.<br> Value length limit: 64 characters. | `firstName`
Full name | Displayed in Yandex Cloud services.<br> Value length limit: 64 characters. | `name`
Email | Used to send notifications from Yandex Cloud services.<br>Example: `ivanov@example.com`.<br> Value length limit: 256 characters. | `email`
Phone | Used to send notifications from Yandex Cloud services.<br>Example: +71234567890.<br> Value length limit: 64 characters. | `phone`
Profile image | Displayed in Yandex Cloud services. The image must be provided in Base64 format.<br> Value length limit: 204,800 characters. | `thumbnailPhoto`
Group membership | Used for dynamic mapping of group members. | `member`

{% note warning %}

The `thumbnailPhoto` attribute value exceeding the length limit is ignored. If the value of a different attribute exceeds the limit, the value part that goes beyond the limit is truncated.

{% endnote %}

>Attribute mapping example:
>
>![image](../../../_assets/organization/keycloak-saml-mapping.png)

## Authentication {#test-auth}

When you finish setting up SSO, test that everything works properly:

1. Open your browser in guest or private browsing mode.

1. Use this URL to log in to the management console:

   ```
   https://console.yandex.cloud/federations/<federation_ID>
   ```

   {% cut "How to get a federation ID" %}

   1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization).
   1. In the left-hand panel, select ![VectorSquare](../../../_assets/console-icons/vector-square.svg) **Federations**.
   1. Select the required federation and copy the **Identifier** field value on the federation info page.

   {% endcut %}
   
   The browser will redirect you to the Keycloak authentication page.

1. Enter your credentials and click **Sign in**.

On successful authentication, the IdP server will redirect you to the ACS URL you specified in the Keycloak settings and then to the [management console](https://console.yandex.cloud) home page. In the top-right corner, you will see being logged in to the console as a federated user.