Compare languages | The user-authn module: usage

An example of the module configuration

Пример конфигурации модуля

The example shows the configuration of the ‘user-authn` module in the Deckhouse Kubernetes Platform.

В примере представлена конфигурация модуля user-authn в Deckhouse Kubernetes Platform.

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: user-authn spec: version: 2 enabled: true settings: kubeconfigGenerator:

  • id: direct masterURI: https://159.89.5.247:6443 description: “Direct access to kubernetes API” publishAPI: enabled: true

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: user-authn spec: version: 2 enabled: true settings: kubeconfigGenerator:

  • id: direct masterURI: https://159.89.5.247:6443 description: “Direct access to kubernetes API” publishAPI: enabled: true

Configuring a provider

Примеры настройки провайдера

GitHub

GitHub

The example shows the provider’s settings for integration with GitHub.

В примере представлены настройки провайдера для интеграции с GitHub.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: github spec: type: Github displayName: My Company Github github: clientID: plainstring clientSecret: plainstring

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: github spec: type: Github displayName: My Company GitHub github: clientID: plainstring clientSecret: plainstring

In your GitHub organization, create a new application:

В организации GitHub необходимо создать новое приложение.

To do this, go to Settings -> Developer settings -> OAuth Aps -> Register a new OAuth application and specify the https://dex.<modules.publicDomainTemplate>/callback address as the Authorization callback URL.

Для этого выполните следующие шаги:

  • перейдите в Settings -> Developer settings -> OAuth Aps -> Register a new OAuth application и в качестве Authorization callback URL укажите адрес https://dex.<modules.publicDomainTemplate>/callback.

Paste the generated Client ID and Client Secret into the DexProvider custom resource.

Полученные Client ID и Client Secret укажите в Custom Resource DexProvider.

If the GitHub organization is managed by the client, go to Settings -> Applications -> Authorized OAuth Apps -> <name of created OAuth App> and request confirmation by clicking on Send Request. Then ask the client to confirm the request that will be sent to him by email.

Если организация GitHub находится под управлением клиента, перейдите в Settings -> Applications -> Authorized OAuth Apps -> <name of created OAuth App> и нажмите Send Request для подтверждения. Попросите клиента подтвердить запрос, который придет к нему на email.

GitLab

GitLab

The example shows the provider’s settings for integration with GitLab.

В примере представлены настройки провайдера для интеграции с GitLab.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: gitlab spec: type: Gitlab displayName: Dedicated GitLab gitlab: baseURL: https://gitlab.example.com clientID: plainstring clientSecret: plainstring groups:

  • administrators
  • users

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: gitlab spec: type: Gitlab displayName: Dedicated GitLab gitlab: baseURL: https://gitlab.example.com clientID: plainstring clientSecret: plainstring groups:

  • administrators
  • users

Create a new application in the GitLab project.

В GitLab проекта необходимо создать новое приложение.

To do this, you need to:

  • self-hosted: go to Admin area -> Application -> New application and specify the https://dex.<modules.publicDomainTemplate>/callback address as the Redirect URI (Callback url) and set scopes read_user, openid;
  • cloud gitlab.com: under the main project account, go to User Settings -> Application -> New application and specify the https://dex.<modules.publicDomainTemplate>/callback address as the Redirect URI (Callback url); also, don’t forget to set scopes read_user, openid;
  • (for GitLab version starting with 16) enable the Trusted/Trusted applications are automatically authorized on GitLab OAuth flow checkbox when creating an application.

Для этого выполните следующие шаги:

  • self-hosted: перейдите в Admin area -> Application -> New application и в качестве Redirect URI (Callback url) укажите адрес https://dex.<modules.publicDomainTemplate>/callback, выберите scopes: read_user, openid;
  • cloud gitlab.com: под главной учетной записью проекта перейдите в User Settings -> Application -> New application и в качестве Redirect URI (Callback url) укажите адрес https://dex.<modules.publicDomainTemplate>/callback, выберите scopes: read_user, openid;
  • (для GitLab версии 16 и выше) включить опцию Trusted/Trusted applications are automatically authorized on GitLab OAuth flow при создании приложения.

Paste the generated Application ID and Secret into the DexProvider custom resource.

Полученные Application ID и Secret укажите в Custom Resource DexProvider.

Atlassian Crowd

Atlassian Crowd

The example shows the provider’s settings for integration with Atlassian Crowd.

В примере представлены настройки провайдера для интеграции с Atlassian Crowd.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: crowd spec: type: Crowd displayName: Crowd crowd: baseURL: https://crowd.example.com/crowd clientID: plainstring clientSecret: plainstring enableBasicAuth: true groups:

  • administrators
  • users

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: crowd spec: type: Crowd displayName: Crowd crowd: baseURL: https://crowd.example.com/crowd clientID: plainstring clientSecret: plainstring enableBasicAuth: true groups:

  • administrators
  • users

Create a new Generic application in the corresponding Atlassian Crowd project.

В соответствующем проекте Atlassian Crowd необходимо создать новое Generic-приложение.

To do this, go to Applications -> Add application.

Для этого выполните следующие шаги:

  • перейдите в Applications -> Add application.

Paste the generated Application Name and Password into the DexProvider custom resource.

Полученные Application Name и Password укажите в Custom Resource DexProvider.

CROWD groups are specified in the lowercase format for the custom resource DexProvider.

Группы CROWD укажите в lowercase-формате для Custom Resource DexProvider.

Bitbucket Cloud

Bitbucket Cloud

The example shows the provider’s settings for integration with Bitbucket Cloud.

В примере представлены настройки провайдера для интеграции с Bitbucket.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: bitbucket spec: type: BitbucketCloud displayName: Bitbucket bitbucketCloud: clientID: plainstring clientSecret: plainstring includeTeamGroups: true teams:

  • administrators
  • users

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: gitlab spec: type: BitbucketCloud displayName: Bitbucket bitbucketCloud: clientID: plainstring clientSecret: plainstring includeTeamGroups: true teams:

  • administrators
  • users

Create a new OAuth consumer in the Bitbucket’s team menu.

Для настройки аутентификации необходимо в Bitbucket в меню команды создать нового OAuth consumer.

To do this, go to Settings -> OAuth consumers -> New application and specify the https://dex.<modules.publicDomainTemplate>/callback address as the Callback URL. Also, allow access for Account: Read and Workspace membership: Read.

Для этого выполните следующие шаги:

  • перейдите в Settings -> OAuth consumers -> New application и в качестве Callback URL укажите адрес https://dex.<modules.publicDomainTemplate>/callback, разрешите доступ для Account: Read и Workspace membership: Read.

Paste the generated Key and Secret into the DexProvider custom resource.

Полученные Key и Secret укажите в Custom Resource DexProvider.

OIDC (OpenID Connect)

OIDC (OpenID Connect)

Authentication through the OIDC provider requires registering a client (or “creating an application”). Please refer to the provider’s documentation on how to do it (e.g., Okta, Keycloak, Gluu).

Аутентификация через OIDC-провайдера требует регистрации клиента (или создания приложения). Сделайте это по документации вашего провайдера (например, Okta, Keycloak, Gluu или Blitz).

Paste the generated clientID and clientSecret into the DexProvider custom resource.

Полученные в ходе выполнения инструкции clientID и clientSecret укажите в Custom Resource DexProvider.

Keycloak

Ниже можно ознакомиться с некоторыми примерами.

After selecting a realm to configure, adding a user in the Users section, and creating a client in the Clients section with authentication enabled, which is required to generate the clientSecret, you need to perform the following steps:

Keycloak

  • Create a scope named groups in the Client scopes section and assign it the predefined mapping groups. (“Client scopes” → “Client scope details” → “Mappers” → “Add predefined mappers”)
  • In the previously created client, add this scope in the Client scopes tab (“Clients” → “Client details” → “Client Scopes” → “Add client scope”).
  • In the “Valid redirect URIs”, “Valid post logout redirect URIs”, and “Web origins” fields of the client configuration, specify https://dex.<publicDomainTemplate>/*, where publicDomainTemplate is a value of the parameter in the global module config.

После выбора realm для настройки, добавления пользователя в Users и создания клиента в разделе Clients с включенной аутентификацией, которая необходима для генерации clientSecret, выполните следующие шаги:

The example shows the provider’s settings for integration with Keycloak.

  • Создайте в разделе Client scopes scope с именем groups, и назначьте ему предопределенный маппинг groups («Client scopes» → «Client scope details» → «Mappers» → «Add predefined mappers»).
  • В созданном ранее клиенте добавьте данный scope во вкладке Client scopes («Clients → «Client details» → «Client Scopes» → «Add client scope»).
  • В полях «Valid redirect URIs», «Valid post logout redirect URIs» и «Web origins» конфигурации клиента укажите https://dex.<publicDomainTemplate>/*, где publicDomainTemplate – это указанный шаблон DNS-имен кластера в модуле global.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: keycloak spec: type: OIDC displayName: My Company Keycloak oidc: issuer: https://keycloak.my-company.com/realms/myrealm # Use the name of your realm clientID: plainstring clientSecret: plainstring insecureSkipEmailVerified: true
getUserInfo: true scopes:

  • openid
  • profile
  • email
  • groups

В примере представлены настройки провайдера для интеграции с Keycloak:

When using Keycloak as an Identity Provider, remove the Email verified mapping in the Client scopes tab (“Client Scopes” → “Email” → “Mappers”). This is necessary for correct processing of true value of insecureSkipEmailVerified field and to grant permissions to unverified users.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: keycloak spec: type: OIDC displayName: My Company Keycloak oidc: issuer: https://keycloak.my-company.com/realms/myrealm # Используйте имя вашего realm clientID: plainstring clientSecret: plainstring insecureSkipEmailVerified: true getUserInfo: true scopes:

  • openid
  • profile
  • email
  • groups

Okta

При использовании Keycloak, как Identity Provider во вкладке Client scopes удалите маппинг Email verified («Client Scopes» → «Email» → «Mappers»). Это необходимо для корректной обработки значения true поля insecureSkipEmailVerified и правильной выдачи прав неверифицированным пользователям.

The example shows the provider’s settings for integration with Okta.

Okta

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: okta spec: type: OIDC displayName: My Company Okta oidc: issuer: https://my-company.okta.com clientID: plainstring clientSecret: plainstring insecureSkipEmailVerified: true getUserInfo: true

В примере представлены настройки провайдера для интеграции с Okta:

Blitz Identity Provider

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: okta spec: type: OIDC displayName: My Company Okta oidc: issuer: https://my-company.okta.com clientID: plainstring clientSecret: plainstring insecureSkipEmailVerified: true getUserInfo: true

Note that you must specify a URL to redirect the user after authorization when registering the application with the Blitz Identity Provider. When using DexProvider, you must specify https://dex.<publicDomainTemplate>/, where publicDomainTemplate is the cluster’s DNS name template as defined in the global module.

Blitz Identity Provider

The example below shows the provider settings for integration with Blitz Identity Provider.

На стороне провайдера Blitz Identity Provider при регистрации приложения необходимо указать URL для перенаправления пользователя после авторизации. При использовании DexProvider необходимо указать https://dex.<publicDomainTemplate>/, где publicDomainTemplateуказанный в модуле global шаблон DNS-имен кластера.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: blitz spec: displayName: Blitz Identity Provider oidc: basicAuthUnsupported: false claimMapping: email: email groups: your_claim # Claim for getting user groups, configured on the Blitz clientID: clientID clientSecret: clientSecret getUserInfo: true insecureSkipEmailVerified: true # Set to true if there is no need to verify the user’s email insecureSkipVerify: false issuer: https://yourdomain.idblitz.ru/blitz promptType: consent scopes:

  • profile
  • openid userIDKey: sub userNameKey: email type: OIDC

В примере представлены настройки провайдера для интеграции с Blitz Identity Provider:

For the application logout to work correctly (the token being revoked so that re-authorization is required), set login as the value of the ‘promptType` parameter.

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: blitz spec: displayName: Blitz Identity Provider oidc: basicAuthUnsupported: false claimMapping: email: email groups: your_claim # Claim для получения групп пользователя, группы пользователя настраиваются на стороне провайдера Blitz Identity Provider clientID: clientID clientSecret: clientSecret getUserInfo: true insecureSkipEmailVerified: true # Установить true, если нет необходимости в проверке email пользователя insecureSkipVerify: false issuer: https://yourdomain.idblitz.ru/blitz promptType: consent scopes:

  • profile
  • openid userIDKey: sub userNameKey: email type: OIDC

To ensure granular user access to applications, you have to:

Чтобы корректно отрабатывал выход из приложений (происходил отзыв токена и требовалась повторная авторизация), нужно установить login в значении параметра promptType.

  • Add the allowedUserGroups parameter to the ModuleConfig of the target application.
  • Add the user to the groups (group names should be the same for Blitz and Deckhouse).

Для обеспечения гранулированного доступа пользователя к приложениям необходимо:

Below is an example for prometheus:

  • добавить параметр allowedUserGroups в ModuleConfig нужного приложения;
  • добавить группы к пользователю (наименования групп должны совпадать как на стороне Blitz, так и на стороне Deckhouse).

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: prometheus spec: version: 2 settings: auth: allowedUserGroups:

  • adm-grafana-access
  • grafana-access

Пример для Prometheus:

LDAP

yaml apiVersion: deckhouse.io/v1alpha1 kind: ModuleConfig metadata: name: prometheus spec: version: 2 settings: auth: allowedUserGroups:

  • adm-grafana-access
  • grafana-access

The example shows the provider’s settings for integration with Active Directory.

LDAP

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: active-directory spec: type: LDAP displayName: Active Directory ldap: host: ad.example.com:636 insecureSkipVerify: true

В примере представлены настройки провайдера для интеграции с Active Directory:

bindDN: cn=Administrator,cn=users,dc=example,dc=com bindPW: admin0!

yaml apiVersion: deckhouse.io/v1 kind: DexProvider metadata: name: active-directory spec: type: LDAP displayName: Active Directory ldap: host: ad.example.com:636 insecureSkipVerify: true

usernamePrompt: Email Address

bindDN: cn=Administrator,cn=users,dc=example,dc=com bindPW: admin0!

userSearch: baseDN: cn=Users,dc=example,dc=com filter: “(objectClass=person)” username: userPrincipalName idAttr: DN emailAttr: userPrincipalName nameAttr: cn

usernamePrompt: Email Address

groupSearch: baseDN: cn=Users,dc=example,dc=com filter: “(objectClass=group)” userMatchers:

  • userAttr: DN groupAttr: member nameAttr: cn

userSearch: baseDN: cn=Users,dc=example,dc=com filter: “(objectClass=person)” username: userPrincipalName idAttr: DN emailAttr: userPrincipalName nameAttr: cn

To configure authentication, create a read-only user (service account) in LDAP.

groupSearch: baseDN: cn=Users,dc=example,dc=com filter: “(objectClass=group)” userMatchers:

  • userAttr: DN groupAttr: member nameAttr: cn

Specify the generated user path and password in the bindDN and bindPW fields of the DexProvider custom resource.

  1. You can omit these settings of anonymous read access is configured for LDAP.
  2. Enter the password into the bindPW in the plain text format. Strategies involving the passing of hashed passwords are not supported.

Для настройки аутентификации заведите в LDAP read-only-пользователя (service account).

Configuring the OAuth2 client in Dex for connecting an application

Полученные путь до пользователя и пароль укажите в параметрах bindDN и bindPW Custom Resource DexProvider.

  1. Если в LDAP настроен анонимный доступ на чтение, настройки можно не указывать.
  2. В параметре bindPW укажите пароль в plain-виде. Стратегии с передачей хэшированных паролей не предусмотрены.

This configuration is suitable for applications that can independently perform oauth2 authentication without using an oauth2 proxy. The DexClient custom resource enables applications to use dex.

Настройка OAuth2-клиента в Dex для подключения приложения

Этот вариант настройки подходит приложениям, которые имеют возможность использовать OAuth2-аутентификацию самостоятельно, без помощи oauth2-proxy. Чтобы позволить подобным приложениям взаимодействовать с Dex, используется Custom Resource DexClient.

yaml apiVersion: deckhouse.io/v1 kind: DexClient metadata: name: myname namespace: mynamespace spec: redirectURIs:

  • https://app.example.com/callback
  • https://app.example.com/callback-reserve allowedGroups:
  • Everyone
  • admins trustedPeers:
  • opendistro-sibling

yaml apiVersion: deckhouse.io/v1 kind: DexClient metadata: name: myname namespace: mynamespace spec: redirectURIs:

  • https://app.example.com/callback
  • https://app.example.com/callback-reserve allowedGroups:
  • Everyone
  • admins trustedPeers:
  • opendistro-sibling

After the DexClient custom resource is created, Dex will register a client with a dex-client-myname@mynamespace ID (clientID).

The client access password (clientSecret) will be stored in the secret object:

После создания такого ресурса в Dex будет зарегистрирован клиент с идентификатором (clientID) dex-client-myname@mynamespace.

yaml apiVersion: v1 kind: Secret metadata: name: dex-client-myname namespace: mynamespace type: Opaque data: clientSecret: c2VjcmV0

Пароль доступа к клиенту (clientSecret) сохранится в секрете:

yaml apiVersion: v1 kind: Secret metadata: name: dex-client-myname namespace: mynamespace type: Opaque data: clientSecret: c2VjcmV0

An example of creating a static user

Create a password and enter its hash in the password field.

Пример создания статического пользователя

Use the command below to calculate the password hash:

Придумайте пароль и укажите его хэш-сумму в поле password.

shell echo “$password” | htpasswd -BinC 10 “” | cut -d: -f2 | base64 -w0

Для вычисления хэш-суммы пароля воспользуйтесь командой:

If the htpasswd command is not available, install the appropriate package:

shell echo “$password” | htpasswd -BinC 10 “” | cut -d: -f2 | base64 -w0

  • apache2-utils — for Debian-based distributions.
  • httpd-tools — for CentOS-based distributions.
  • apache2-htpasswd — for ALT Linux.

Если команда htpasswd недоступна, установите соответствующий пакет:

Alternatively, you can use the online service to calculate the password hash.

  • apache2-utils — для дистрибутивов, основанных на Debian;
  • httpd-tools — для дистрибутивов, основанных на CentOS;
  • apache2-htpasswd — для ALT Linux.

Note that in the below example the ttl parameter is set.

Также можно воспользоваться онлайн-сервисом.

Обратите внимание, что в приведенном примере указан ttl.

yaml apiVersion: deckhouse.io/v1 kind: User metadata: name: admin spec: email: admin@yourcompany.com password: $2a$10$etblbZ9yfZaKgbvysf1qguW3WULdMnxwWFrkoKpRH1yeWa5etjjAa ttl: 24h

yaml apiVersion: deckhouse.io/v1 kind: User metadata: name: admin spec: email: admin@yourcompany.com password: $2a$10$etblbZ9yfZaKgbvysf1qguW3WULdMnxwWFrkoKpRH1yeWa5etjjAa ttl: 24h

Example of adding a static user to a group

Пример добавления статического пользователя в группу

yaml apiVersion: deckhouse.io/v1alpha1 kind: Group metadata: name: admins spec: name: admins members:

  • kind: User name: admin

yaml apiVersion: deckhouse.io/v1alpha1 kind: Group metadata: name: admins spec: name: admins members:

  • kind: User name: admin

How to set permissions for a user or group

Parameters in the custom resource ClusterAuthorizationRule are used for configuration.

Выдача прав пользователю или группе

 

Для настройки используются параметры в Custom Resource ClusterAuthorizationRule.