[Yandex Cloud documentation](../../../../index.md) > [Yandex Identity Hub](../../../index.md) > [Tutorials](../../index.md) > [Managing identity federations](../index.md) > User group mapping > User group mapping in Keycloak

# User group mapping in Keycloak

To configure user group mapping in [Keycloak](https://www.keycloak.org/) and user groups in the [identity federation](../../../concepts/add-federation.md):

1. [Create a federation in Yandex Identity Hub](#create-federation).
1. [Add a Keycloak certificate to the federation](#add-certificate)
1. [Create and configure a SAML application in Keycloak](#keycloak-settings).
1. [Configure group mapping on the Keycloak side](#kc-mapping).
1. [Configure group mapping on the federation side](#org-mapping).
1. [Test authentication](#test-auth).

{% note info %}

All examples were tested with Keycloak version `21.1.2`.

{% endnote %}

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

{% note tip %}

If you already have an active Keycloak server, check the Keycloak settings against the recommendations in this guide, and use your existing server instead of creating a new one. In this case, you can go directly to the [Configure group mapping on the Keycloak](#kc-mapping) side section.

{% endnote %}

1. Set up a local Keycloak server for testing:

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

    1. Install and run a Docker container with Keycloak version 21.1.2:

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

    As long as the container is running, the Keycloak administrator account will be available at [http://localhost:8080/admin](http://localhost:8080/admin) or [http://0.0.0.0:8080/admin](http://0.0.0.0:8080/admin). The default login credentials are as follows:

    * **User name or email**: `admin`.
    * **Password**: `Pa55w0rd`.

    {% 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. For more information, see [this Keycloak guide](https://www.keycloak.org/server/hostname).

    {% endnote %}

1. Get the certificate used for signing in Keycloak:

    1. Log in to the Keycloak administrator account at: `http://<IP_or_URL_Keycloak>:8080/admin`.

        If you are using a local server from a Docker image, the default login credentials are as follows:

        * URL: [http://0.0.0.0:8080/admin](http://0.0.0.0:8080/admin).
        * **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 to a file named `keycloak-cert.cer` in the following format:

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

      You will need this certificate later when setting up the identity federation.

## Create a Yandex Identity Hub 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. Enter a name for the federation, e.g., `demo-federation`. 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:

          ```text
          http://<Keycloak>_IP_or_URL:8080/realms/master
          ```

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

          ```text
          http://<Keycloak>_IP_or_URL:8080/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. (Optional) To make sure that all authentication requests from Yandex Cloud contain a digital signature, enable **Sign authentication requests**. You will need to install a Yandex Cloud SAML certificate on the IdP side.

          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 [download and install](../../../operations/setup-federation.md#add-certificate-idp) a Yandex Cloud certificate even after creating a federation.

          You will need this certificate later when setting up the client in Keycloak.

      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**.

{% endlist %}

## Add the Keycloak certificate to the federation {#add-certificate}

To make sure that Yandex Identity Hub can verify the Keycloak server certificate during authentication, 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 `demo-federation` to add your certificate to.

  1. Click **Certificates** under **Adding a certificate** at the bottom of the page.

  1. Enter a name for the certificate and specify the path to the `keycloak-cert.cer` file.

  1. Click **Add**.

{% 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 %}

## Create and configure 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: `http://<IP_or_URL_Keycloak>:8080/admin`.

    If you are using a local server from a Docker image, the default login credentials are as follows:

    * URL: [http://0.0.0.0:8080/admin](http://0.0.0.0:8080/admin).
    * **User name or email**: `admin`.
    * **Password**: `Pa55w0rd`.

1. Create a SAML application:

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

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

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

        {% cut "How to get the 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. Click **Next**.
    1. Specify the ACS redirect URL,, in the following fields:

        * **Home URL**
        * **Valid Redirect URIs**
        * **IDP Initiated SSO Relay State**
    
        
        {% 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. Click **Save**.

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

    1. Enable the following options:

       * **Include AuthnStatement**
       * **Sign Assertions**
       * **Force name ID format**
       * **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 `username` as **Name ID Format**.

    1. Click **Save**.

1. (Optional) 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:

    1. On the **Keys** tab of the SAML application, check that the **Client Signature Required** option is enabled.
    1. Click the **Import key** button under the automatically generated certificate and select **Certificate PEM** in the **Archive Format** field.
    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 **Import**.
    1. Enable the **Encrypt Assertions** option.
    1. In the window that opens, select the **Generate** method and click **Confirm**.
    1. Click **Import key** under the generated certificate and select **Certificate PEM** in the **Archive Format** field.
    1. Click **Browse** and select the certificate you are going to use to sign authentication requests. The certificate is available for download on the Yandex Identity Hub federation info page in the **Sign authentication requests** field.
    1. Click **Import**.

## Configure group mapping on the Keycloak side {#kc-mapping}

1. Create a user:

    1. In the left-hand panel, select **Users**.
    1. Click **Add user** and enter a username, e.g., `demo_user1`.
    1. Click **Create**.
    1. In the **Credentials** tab, click **Set Password** and enter a password. For easier testing, disable the **Temporary** option.

1. Create a group and add a user to it:

    1. In the left-hand panel, select **Groups**.
    1. Click **Create group** and enter a name for the group, e.g., `kc_demo_group`.
    1. Click the group name, click **Add member** on the **Members** tab, and add the `demo_user1` user from the list to the group.

1. Add a mapper to the Keycloak application:

    1. In the left-hand panel, select **Clients** and select the previously created application from the list.
    1. Navigate to the **Client scopes** tab and select the ACS URL with the `-dedicated` postfix: `<ACS_URL>-dedicated`.

        
        {% 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. On the **Mappers** tab, click **Configure a new mapper**. Select **Group list** from the drop-down list.
    1. Specify the following mapper settings:

        * **Name**: `group_mapper`
        * **Group attribute name**: `member`
        * **SAML Attribute NameFormat**: `Basic`
        * **Single Group Attribute**: `On`
        * **Full group path**: `Off`

    1. Click **Save**.

## Configure group mapping on the federation side {#org-mapping}

{% note info %}

To configure [user group](../../../concepts/user-pools.md) mapping on the Yandex Cloud side, [assign](../../../../iam/operations/roles/grant.md#resource) the user one of the following [roles](../../../../iam/concepts/access-control/roles.md):

* [`organization-manager.federations.editor`](../../../security/index.md#organization-manager-federations-editor)
* [`organization-manager.federations.admin`](../../../security/index.md#organization-manager-federations-admin)
* [`organization-manager.editor`](../../../security/index.md#organization-manager-editor)
* [`organization-manager.admin`](../../../security/index.md#organization-manager-admin)

The role must be assigned for the groups you intend to map.

{% endnote %}

{% list tabs group=instructions %}

- Cloud Center UI {#cloud-center}

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

  1. [Create a user group](../../../operations/create-group.md) named `yc_demo_group` in Yandex Identity Hub and [authorize it](../../../operations/access-group.md) to view resources in the cloud or a separate folder (the `viewer` role).

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

  1. Select `demo-federation` you created previously and navigate to the **IdP group** tab.

  1. Enable **Mapping group in IdP**.

  1. Click **Add group**.

  1. In the **Group name** field, enter the group name in Keycloak: `kc_demo_group`.

  1. In the **IAM group** field, select the `yc_demo_group` group you created in Yandex Identity Hub from the list.

  1. Click **Save**.

- Terraform {#tf}

  1. Describe the properties of the new resources in the Terraform configuration file:

      ```hcl
      # Creating a user group
      resource "yandex_organizationmanager_group" "my-group" {
        name            = "yc_demo_group"
        organization_id = "demo-federation"
      }

      # Assigning the viewer role for a folder
      resource "yandex_resourcemanager_folder_iam_member" "viewers" {
        folder_id = "<folder_ID>"
        role      = "viewer"
        member    = "group:${yandex_organizationmanager_group.my-group.id}"
      }

      # Enabling federated user group mapping
      resource "yandex_organizationmanager_group_mapping" "my_group_map" {
        federation_id = "demo-federation"
        enabled       = true
      }

      # Configuring a federated user group mapping
      resource "yandex_organizationmanager_group_mapping_item" "group_mapping_item" {
        federation_id     = "demo-federation"
        internal_group_id = yandex_organizationmanager_group.my-group.id
        external_group_id = "kc_demo_group"

        depends_on = [yandex_organizationmanager_group_mapping.group_mapping]
      }
      ```

      Where:
      * `folder_id`: Folder the role is assigned for.

      For more information, see the descriptions of the [yandex_organizationmanager_group_mapping](../../../../terraform/resources/organizationmanager_group_mapping.md) and [yandex_organizationmanager_group_mapping_item](../../../../terraform/resources/organizationmanager_group_mapping_item.md) resources in the Terraform provider guides.

  1. Create the resources:

     1. In the terminal, navigate to the configuration file directory.
     1. Make sure the configuration is correct using this command:
     
        ```bash
        terraform validate
        ```
     
        If the configuration is valid, you will get this message:
     
        ```bash
        Success! The configuration is valid.
        ```
     
     1. Run this command:
     
        ```bash
        terraform plan
        ```
     
        You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
     1. Apply the configuration changes:
     
        ```bash
        terraform apply
        ```
     
     1. Type `yes` and press **Enter** to confirm the changes.

{% endlist %}

## Test authentication {#test-auth}

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

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

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

    {% cut "How to get the 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 %}

    If you have set everything up correctly, the browser will redirect you to the Keycloak authentication page.

1. Enter the username and password for the test federated user (`demo_user1`) 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.

1. Make sure the created `demo_user1` belongs to `yc_demo_group` and has the viewer permissions for resources according to the role assigned to the group.