[Yandex Cloud documentation](../../index.md) > [Tutorials](../index.md) > [Security](index.md) > Managing identity federations > Active Directory authentication

# Authentication via Active Directory

With an [identity federation](../../organization/concepts/add-federation.md), you can set up Single Sign-On (SSO) and use Microsoft Active Directory in conjunction with [Microsoft Active Directory Federation Services](https://docs.microsoft.com/en-us/windows-server/identity/active-directory-federation-services) (AD FS) for cloud authentication.

To configure SSO:

1. [Create a federation in your organization](#create-federation).

1. [Specify certificates for the federation](#add-certificate).

1. [Add users to your organization](#add-users).

1. [Test authentication](#test-auth).

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

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

1. An operational AD FS farm.

    If you do not have the an AD FS farm configured yet, follow these steps to set one up:

    1. [Deploy and configure Active Directory Domain Services (AD DS)](https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/deploy/install-active-directory-domain-services--level-100-) if you have not already done so. You must have AD AS to deploy AD FS.
    1. [Deploy and configure an AD FS](https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/deployment/deploying-a-federation-server-farm) farm of one or more servers.

        {% note tip %}

        Add multiple servers to your AD FS farm for fault tolerance.

        In which case SSO will be available even if some of the servers go down.

        {% endnote %}

1. A valid SSL certificate for use in AD FS. If you do not have a valid certificate, get one.

    To prevent browsers from blocking the authentication page when using SSO, the certificate must satisfy the following requirements:

    * The certificate must be trusted by devices and users within the Active Directory forest.
    * The certificate's `Subject Name` property and `Alternative Name` extension must contain the AD FS farm's FQDN.

        {% cut "How to get a farm FQDN" %}
        
        1. Connect to any server in the AD FS farm and open the PowerShell console.
        
        1. Get the federation service endpoint:
           
            ```powershell
            Get-AdfsEndpoint -AddressPath /adfs/ls/ | Select FullUrl
            ```
           
           The endpoint contains the FQDN of the AD FS farm and has the following format:
           
           ```text
           https://<AD_FS_farm_FQDN>/adfs/ls/
           ```
        
        {% endcut %}

## Create a federation in your organization {#create-federation}

To create a 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.

  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, specify a link in `http://<AD_FS_farm_FQDN>/adfs/services/trust` format.

     {% cut "How to get a farm FQDN" %}
     
     1. Connect to any server in the AD FS farm and open the PowerShell console.
     
     1. Get the federation service endpoint:
        
         ```powershell
         Get-AdfsEndpoint -AddressPath /adfs/ls/ | Select FullUrl
         ```
        
        The endpoint contains the FQDN of the AD FS farm and has the following format:
        
        ```text
        https://<AD_FS_farm_FQDN>/adfs/ls/
        ```
     
     {% endcut %}

  1. In the **Single Sign-On method** field, choose **POST**.

  1. In the **Link to the IdP login page** field, specify a link in `https://<AD_FS_farm_FQDN>/adfs/ls/` format.

     You can only use HTTP and HTTPS in a link.

  1. Enable **Automatically create users** to add authenticated users to your organization automatically. If this option is disabled, the user will not be able to use Yandex Cloud until they are [added to the organization manually](../../organization/operations/add-account.md#add-user-sso).

      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 this configuration, you will need to install a Yandex Cloud certificate for your IdP.

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

  1. Enable **Mandatory re-authentication (ForceAuthn) in IdP** to set [ForceAuthn](../../organization/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:

        ```bash
        yc organization-manager federation saml create --name my-federation \
          --organization-id <organization_ID> \
          --auto-create-account-on-login \
          --cookie-max-age 12h \
          --issuer "http://example.com/adfs/services/trust" \
          --sso-url "https://example.com/adfs/ls/" \
          --sso-binding POST \
          --encrypted-assertions \
          --force-authn
        ```

        Where:

        * `--name`: Federation name. It must be unique within the folder.
        * `--organization-id`: [Organization ID](../../organization/operations/organization-get-id.md).
        * `--auto-create-account-on-login`: Option enabling the automatic creation of new cloud users after authentication using an identity provider (IdP).

            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 via an identity provider. In this case, you can manage a list of users allowed to use Yandex Cloud resources.

        * `--cookie-max-age`: Time before the browser asks the user to re-authenticate.
        * `--issuer`: ID of the identity provider that will be used for authentication.

            Specify a link in `http://<AD_FS_farm_FQDN>/adfs/services/trust` format.

            {% cut "How to get a farm FQDN" %}
            
            1. Connect to any server in the AD FS farm and open the PowerShell console.
            
            1. Get the federation service endpoint:
               
                ```powershell
                Get-AdfsEndpoint -AddressPath /adfs/ls/ | Select FullUrl
                ```
               
               The endpoint contains the FQDN of the AD FS farm and has the following format:
               
               ```text
               https://<AD_FS_farm_FQDN>/adfs/ls/
               ```
            
            {% endcut %}

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

            Specify a link in `https://<AD_FS_farm_FQDN>/adfs/ls/` format.

            You can only use HTTP and HTTPS in a link.

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

        * (Optional) `--encrypted-assertions`: Flag enabling a digital signature for authentication requests.
          
          If set to `true`, all authentication requests from Yandex Cloud will contain a digital signature.

            You can [download and install](../../organization/operations/setup-federation.md#add-certificate-idp) a Yandex Cloud certificate even after creating a federation.

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

- Terraform {#tf}

  If you do not have Terraform yet, [install it and configure the Yandex Cloud provider](../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:

      ```hcl
      resource "yandex_organizationmanager_saml_federation" federation {
        name            = "my-federation"
        organization_id = "<organization_ID>"
        auto_create_account_on_login = "true"
        issuer          = "http://example.com/adfs/services/trust"
        sso_url         = "https://example.com/adfs/ls/"
        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](../../organization/operations/organization-get-id.md).
      * `labels`: Set of key/value label pairs assigned to the federation. This is an optional setting.
      * `issuer`: Identity provider (IdP) ID that will be used for authentication.

          Specify a link in `http://<AD_FS_farm_FQDN>/adfs/services/trust` format.

          {% cut "How to get a farm FQDN" %}
          
          1. Connect to any server in the AD FS farm and open the PowerShell console.
          
          1. Get the federation service endpoint:
             
              ```powershell
              Get-AdfsEndpoint -AddressPath /adfs/ls/ | Select FullUrl
              ```
             
             The endpoint contains the FQDN of the AD FS farm and has the following format:
             
             ```text
             https://<AD_FS_farm_FQDN>/adfs/ls/
             ```
          
          {% endcut %}

      * `sso_binding`: 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.

          Specify a link in `https://<AD_FS_farm_FQDN>/adfs/ls/` format.

          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`: Option enabling the automatic creation of new cloud users after authentication using an identity provider.

          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 via an identity provider. 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.

              You can [download and install](../../organization/operations/setup-federation.md#add-certificate-idp) a Yandex Cloud certificate even after creating a federation.

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

- API {#api}

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

      ```json
      {
        "name": "my-federation",
        "organizationId": "<organization_ID>",
        "autoCreateAccountOnLogin": true,
        "cookieMaxAge":"43200s",
        "issuer": "http://example.com/adfs/services/trust",
        "ssoUrl": "https://example.com/adfs/ls/",
        "ssoBinding": "POST",
        "securitySettings": {
          "encryptedAssertions": true,
          "forceAuthn": true
        }
      }
      ```

      Where:

      * `name`: Federation name. It must be unique within the folder.
      * `organizationId`: [Organization ID](../../organization/operations/organization-get-id.md).
      * `autoCreateAccountOnLogin`: Option enabling the automatic creation of new cloud users after authentication using an identity provider (IdP).

         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 via an identity provider. 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 identity provider that will be used for authentication.

          Specify a link in `http://<AD_FS_farm_FQDN>/adfs/services/trust` format.

          {% cut "How to get a farm FQDN" %}
          
          1. Connect to any server in the AD FS farm and open the PowerShell console.
          
          1. Get the federation service endpoint:
             
              ```powershell
              Get-AdfsEndpoint -AddressPath /adfs/ls/ | Select FullUrl
              ```
             
             The endpoint contains the FQDN of the AD FS farm and has the following format:
             
             ```text
             https://<AD_FS_farm_FQDN>/adfs/ls/
             ```
          
          {% endcut %}

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

          Specify a link in `https://<AD_FS_farm_FQDN>/adfs/ls/` format.

          You can only use HTTP and HTTPS in a link.

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

      * `encryptedAssertions`: Flag enabling a digital signature for authentication requests.
        
        If set to `true`, all authentication requests from Yandex Cloud will contain a digital signature.

        You can [download and install](../../organization/operations/setup-federation.md#add-certificate-idp) a Yandex Cloud certificate even after creating a federation.

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

  1. To create a federation, use the [create](../../organization/saml/api-ref/Federation/create.md) REST API method for the [Federation](../../organization/saml/api-ref/Federation/index.md) resource or the [FederationService/Create](../../organization/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.

{% endlist %}

## Specify certificates for the federation {#add-certificate}

When informing Yandex Identity Hub that a user has been authenticated, the identity provider signs the message with its own certificate. To enable Yandex Identity Hub to verify this certificate, add it to your federation:

1. Get an AD FS farm certificate:

    {% list tabs group=instructions %}

    - MMC snap-in

        1. Connect to any server in the AD FS farm and open **Server Manager**.

        1. Open the AD FS management console: **Tools** → **AD FS Management**.

        1. In the window that opens, click **Services** → **Certificates** in the tree on the left.

        1. Right-click the certificate in the **Token-signing** section and select **View certificate**.

        1. In the window that opens, go to the **Details** tab.

        1. Click the **Copy to file** button.

        1. Click **Next**.

        1. Select the format **Base-64 encoded X.509 (.CER)** and click **Next**.

        1. Specify where to save the certificate and under what name, then click **Next**.

        1. Check the certificate export settings and click **Finish**.

    - PowerShell

        1. Connect to any server in the AD FS farm and open the PowerShell console.

        1. Get a `Token-Signing` certificate in Base64 format. To do this, run these commands, specifying the path you want to save the certificate at:

            ```powershell
            $ADFS_CERT_PATH = "<path_to_certificate>/adfs_certificate.cer"
            
            $TEMP_CERT = (Get-AdfsCertificate -CertificateType Token-Signing |
                            where {$_.IsPrimary -eq $true} | Select-Object -First 1
                         ).Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
            
            @(
                '-----BEGIN CERTIFICATE-----'
                [System.Convert]::ToBase64String($TEMP_CERT, 'InsertLineBreaks')
                '-----END CERTIFICATE-----'
            ) | Out-File -FilePath $ADFS_CERT_PATH -Encoding ascii
            
            ```
            
            The certificate will be saved as `adfs_certificate.cer`.

    {% endlist %}

1. Add the farm 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-name my-federation \
            --name "my-certificate" \
            --certificate-file test.pem
          ```

    - API {#api}

      To add a certificate, use the [create](../../organization/saml/api-ref/Certificate/create.md) method for the [Certificate](../../organization/saml/api-ref/Certificate/index.md) resource:

      1. Create the request body by specifying the contents of the certificate's `data` property:

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

      1. Send the request to add the certificate:

          ```bash
          export IAM_TOKEN=CggaAT********
          curl -X POST \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer ${IAM_TOKEN}" \
            -d '@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](../../organization/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 %}

Configure the AD FS farm to notify Yandex Cloud of every successful authentication and then redirect the user to the console. To set up a farm, you will need information about the federation you [created earlier](#create-federation).

{% note info %}

This setup guide is for Windows Server 2016; for other versions the steps may be different.

{% endnote %}

To configure a farm:

1. [Create a relying party trust](#configure-relying-party-trust).

1. [Configure Claims Mapping](#configure-claims-mapping).

### Create a relying party trust {#configure-relying-party-trust}

Create a _relying party trust_ so that Yandex Cloud can use AD FS for authentication:

1. Connect to any server in the AD FS farm and open **Server Manager**.

1. Open the AD FS management console: **Tools** → **AD FS Management**.

1. In the list of actions, select **Add Relying Party Trust**.

    The wizard window opens.

1. At the Welcome step, select **Claims aware** and click **Start**.

1. At the Select Data Source step, select **Enter data about the relying party manually** and click **Next**.

1. At the Specify Display Name step, enter a name, e.g., `Yandex Cloud` and click **Next**.

1. Skip the Configure Certificate step by clicking **Next**. You will configure certificates later.

1. At the Configure URL step, select **Enable support for the SAML 2.0 WebSSO** protocol and specify 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 %}


   ![image](../../_assets/iam/federations/specify-console-sso-link.png)

   Then click **Next**.

1. At the Configure Identifiers step, enter the same redirect URL as an identifier and click **Add**. Then click **Next**.

1. At the Choose Access Control Policy step, choose who can authenticate using this federation. By default, the **Permit for everyone** policy is selected enabling access for all users.

    You can choose a different policy. For example, to grant access to a specific group of users, select **Permit specific group** and click `<parameter>` to select the groups to get the access permission. [Read more about access control policies](https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/operations/access-control-policies-in-ad-fs).

    ![image](../../_assets/iam/federations/specify-access-policy-ad.png)

    After you select a policy, click **Next**.

1. At the Ready to Add Trust step, check the entered data and click **Close**.

1. (Optional) If you enabled **Sign authentication requests** when [creating the federation](#create-federation) in Yandex Identity Hub, configure the associated relying party trust parameters:
   
   1. Open the context menu of the relying party trust you created and select **Properties**.
   
       This will open the window with relying party trust properties.
   
   1. Go to the **Encryption** tab and add the Yandex Cloud SAML certificate you downloaded [earlier](#create-federation) to sign authentication requests:
   
       1. Click **Browse**.
       1. Select the certificate file, such as `YandexCloud.cer`.
   
            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. Go to the **Signature** tab and add the same certificate:
   
       1. Click **Add**.
       1. Select the certificate file.
   
   1. Click **OK**.
   
   1. Enable required claim encryption and request signing for the created relying party trust:
   
       ```powershell
       Set-AdfsRelyingPartyTrust `
           -TargetName "Yandex Cloud" `
           -EncryptClaims $true `
           -SignedSamlRequestsRequired $true `
           -SamlResponseSignature MessageAndAssertion
       ```

1. (Optional) If you enabled **Mandatory re-authentication (ForceAuthn) in IdP** when [creating the federation](#create-federation) in Yandex Identity Hub, enable forced authentication on the relying party trust side:

    ```powershell
    Set-AdfsRelyingPartyTrust `
        -TargetName "Yandex Cloud" `
        -AlwaysRequireAuthentication $true
    ```

### Configure Claims Mapping {#configure-claims-mapping}

When AD FS authenticates a user, it sends a SAML message to Yandex Cloud confirming successful authentication. The message must contain the `Name ID` that uniquely identifies the user and may also contain other user data, such as name, email, etc. For this you need to configure mapping between the user attributes and Outgoing Claim Types.

#### Review the list of data, attributes, and types of outgoing claims {#explore-claims-list}

User data | Comment | Outgoing Claim Type
------------------- | ----------- | -------------------
Unique user ID | Required attribute. We recommend using one of the unique and fixed Active Directory user attributes: **User-Principal-Name**, **Object-Sid**, **Object-Guid**, or an email address. | `Name ID`
List of groups the user belongs to. | This list is used for group mapping when authenticating the user in Yandex Cloud.<br><br>Use a `Token-Groups` family attribute.<br><br>Depending on the attribute you select, the group list format will vary.<br>For example, if using `Token-Groups - Unqualified Names`, short group names will be provided (e.g., `adfs_group`, `Domain Users`) that do not specify the domain.<br><br>For an example of how to configure group mapping, see [User group mapping in Microsoft Active Directory Federation Services](../../organization/tutorials/federations/group-mapping/adfs.md). | `Group`
Surname | Displayed in Yandex Cloud services. We recommend using the **Surname** attribute.<br> Value length limit: 64 characters. | `Surname`
Name | Displayed in Yandex Cloud services. We recommend using the **Given-Name** attribute.<br> Value length limit: 64 characters. | `Given Name`
Full name | Displayed in Yandex Cloud services. Example: Ivan Ivanov.<br>We recommend using the **Display-Name** attribute.<br> Value length limit: 64 characters. | `Name`
Email | Used to send notifications from Yandex Cloud services. Example: `ivanov@example.com`.<br>We recommend using the **E-Mail-Address** attribute.<br> Value length limit: 256 characters. | `E-Mail Address`
Phone | Used to send notifications from Yandex Cloud services. Example: +71234567890<br>We recommend using the `Telephone-Number` attribute.<br> Value length limit: 64 characters. | `phone`
Profile image | Displayed in Yandex Cloud services.<br>We recommend using the `thumbnailPhoto` attribute. [How to add a profile image](#add-avatar).<br> Value length limit: 204800 characters. | `thumbnailPhoto`

#### Configure attribute and claim mappings {#do-claims-mapping}

{% note info %}

Yandex Cloud [limits the length of values for some attributes](#explore-claims-list) containing user data.

If a value exceeds the limit, its over-the-limit portion will be discarded.

There is an exception: the `thumbnailPhoto` attribute which stores the [user's avatar](#add-avatar). If the value of this attribute exceeds the limit, it will be discarded entirely, and the avatar will not be uploaded.

{% endnote %}

Configure mapping:

1. In the AD FS management console, under **Relying Party Trusts**, right-click the relying party trust created earlier and select **Edit Claim Issuance Policy**.

1. In the window that opens, click **Add Rule**.

1. Select **Send LDAP Attributes as Claims** and click **Next**.

1. On the next page, set up the data to send in the message:

    1. In the **Claim rule name** field, enter a name for the rule, e.g., `Claims mapping`.

    1. In the **Attribute Store** field, click **Active Directory**.

    1. Configure mapping for the mandatory `Name ID` claim by adding an entry to the **Mapping of LDAP attributes** list:

        1. Select the `Name ID` claim type in the **Outgoing Claim Type** column.
        1. Select the required attribute in the **LDAP Attribute** column.

            You can select either [one of the recommended attributes](#explore-claims-list) or another attribute. The selected attribute must be permanent and unique to ensure unambiguous user identification.

            {% note warning %}

            If user ID changes, the user will have to get a new federation account created and will lose access to previous settings and data in Yandex Cloud.

            {% endnote %}

    1. Similarly, configure mapping for the `Group` claim if you are using [user group mapping](../../organization/concepts/add-federation.md#group-mapping).

    
    1. Similarly, configure mappings for the `Name` and `E-Mail Address` claims if you want the user to be able to contact Yandex Cloud support from the [management console](https://center.yandex.cloud/support).


    1. (Optional) Similarly, configure mappings for other claims. The actual list of mappings depends on what [user data](#explore-claims-list) you need to deliver to the Yandex Cloud side after authentication.

        {% cut "How to save a user's avatar image to the `thumbnailPhoto` attribute" %} {#add-avatar}

        1. Prepare images to use as your avatar.

            Make sure the image meets the following requirements:

            * Maximum image file size: 100 KB.
            * Recommended image file size: up to 10 KB; recommended image size: up to 96×96 pixels.

        1. Start PowerShell.

        1. Connect the Active Directory Module for Windows PowerShell using this command:

            ```powershell
            Import-Module ActiveDirectory
            ```

        1. To add a profile image for a single user, run this command:

            ```powershell
            Set-ADUser <username> -Replace @{thumbnailPhoto=([byte[]](Get-Content "<path_to_image>" -Encoding byte))}
            ```

        1. To bulk add profile images for multiple users:

            1. Create a CSV file with a list of usernames and image paths.

                Sample CSV file:

                ```csv
                AD_username, Photo
                smith, C:\Photo\smith.jpg
                jones, C:\Photo\jones.jpg
                ```

            1. Run this command:

                ```powershell
                Import-Csv <path_to_CSV_file> |%{Set-ADUser -Identity $_.AD_username -Replace @{thumbnailPhoto=([byte[]](Get-Content $_.Photo -Encoding byte))}}
                ```

        {% endcut %}

        If you need to configure mappings for `phone` and `thumbnailPhoto`, enter the names of these outgoing claim types manually in the **Outgoing Claim Type** field. You cannot select these types from the drop-down list:

        ![image](../../_assets/iam/federations/specify-claims-mapping-ad.png)

1. Click **Finish**, then click **OK** to close the **Edit Claim Issuance Policy** window.

## Add users to your organization {#add-users}

If you did not enable the **Automatically create users** option when creating the federation, you will have to add federated users to your organization manually.

To do this, you need to know the user's name IDs returned by the identity provider together with the successful authentication response. These are usually the users' primary email addresses. If you do not know what the identity provider returns as the name ID, contact the administrator who had configured authentication for your federation.

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 the [Roles](../../organization/security/index.md#add-role) section.

{% note info %}

To enable a user to access the [management console](https://console.yandex.cloud), assign them a role for the [cloud](../../organization/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 %}

To add federation users to an organization:

{% 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 --name my-federation \
        --name-ids=alice@example.com,bob@example.com,charlie@example.com
      ```

- API {#api}

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

## Test authentication {#test-auth}

Now that you are done configuring SSO, test authentication:

1. Open the browser in guest or incognito mode for a clean new user simulation.

1. Follow the URL to log in to the management console:

   ```url
   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 forwards you to the AD FS authentication page, which by default looks like this:

   ![image](../../_assets/iam/federations/test-auth-with-ad-account.png)

1. Enter your authentication data. By default, you must enter the UPN and password. Then click **Sign in**.

1. On successful authentication, AD FS will redirect you to the ACS URL you specified in the AD FS relying party trust settings, and from there to the management console home page. In the top-right corner, you can see that you are logged in to the console under an Active Directory account.

## What's next {#what-is-next}

* [Assign roles to the new users](../../iam/operations/roles/grant.md)