使用 PostgreSQL 通过 Azure Active Directory 进行身份验证Use Azure Active Directory for authentication with PostgreSQL

本文将介绍如何使用 Azure Database for PostgreSQL 配置 Azure Active Directory 访问权限以及如何使用 Azure AD 令牌进行连接的步骤。This article will walk you through the steps how to configure Azure Active Directory access with Azure Database for PostgreSQL, and how to connect using an Azure AD token.

设置 Azure AD 管理员用户Setting the Azure AD Admin user

只有 Azure AD 管理员用户才能为基于 Azure AD 的身份验证创建/启用用户。Only Azure AD administrator users can create/enable users for Azure AD-based authentication. 我们建议不要使用 Azure AD 管理员进行常规数据库操作,因为这具有提升的用户权限(如 CREATEDB)。We recommend not using the Azure AD administrator for regular database operations, as it has elevated user permissions (e.g. CREATEDB).

若要设置 Azure AD 管理员(可以使用用户或组),请遵循以下步骤To set the Azure AD administrator (you can use a user or a group), please follow the following steps

  1. 在 Azure 门户中,选择要为 Azure AD 启用的 Azure Database for PostgreSQL 实例。In the Azure portal, select the instance of Azure Database for PostgreSQL that you want to enable for Azure AD.
  2. 在“设置”下,选择“Active Directory 管理员”:Under Settings, select Active Directory Admin:

设置 Azure AD 管理员

  1. 在客户租户中选择一个有效的 Azure AD 用户作为 Azure AD 管理员。Select a valid Azure AD user in the customer tenant to be Azure AD administrator.

重要

设置管理员时,将向具有完全管理员权限的 Azure Database for PostgreSQL 服务器添加新用户。When setting the administrator, a new user is added to the Azure Database for PostgreSQL server with full administrator permissions. Azure Database for PostgreSQL 中的 Azure AD 管理员用户将拥有角色 azure_ad_adminThe Azure AD Admin user in Azure Database for PostgreSQL will have the role azure_ad_admin.

每个 PostgreSQL 服务器只能创建一个 Azure AD 管理员,选择另一个管理员将覆盖为服务器配置的现有 Azure AD 管理员。Only one Azure AD admin can be created per PostgreSQL server and selection of another one will overwrite the existing Azure AD admin configured for the server. 可以指定 Azure AD 组(而不是单个用户)来拥有多个管理员。You can specify an Azure AD group instead of an individual user to have multiple administrators. 请注意,你随后将用该组名称登录,以进行管理。Note that you will then sign in with the group name for administration purposes.

使用 Azure AD 连接到 Azure Database for PostgreSQLConnecting to Azure Database for PostgreSQL using Azure AD

以下概要关系图概述了将 Azure AD 身份验证与Azure Database for PostgreSQL 配合使用的工作流:The following high-level diagram summarizes the workflow of using Azure AD authentication with Azure Database for PostgreSQL:

身份验证流

我们将 Azure AD 集成设计为可与常见 PostgreSQL 工具(例如 psql)结合使用,这些工具并非 Azure AD 感知工具,并且在连接到 PostgreSQL 时仅支持指定用户名和密码。We've designed the Azure AD integration to work with common PostgreSQL tools like psql, which are not Azure AD aware and only support specifying username and password when connecting to PostgreSQL. 我们会将 Azure AD 令牌作为密码传递,如上图所示。We pass the Azure AD token as the password as shown in the picture above.

我们当前已测试以下客户端:We currently have tested the following clients:

  • psql 命令行(利用 PGPASSWORD 变量传递令牌,请参阅下文)psql commandline (utilize the PGPASSWORD variable to pass the token, see below)
  • Azure Data Studio(使用 PostgreSQL 扩展)Azure Data Studio (using the PostgreSQL extension)
  • 其他基于 libpq 的客户端(例如常见的应用程序框架和 ORM)Other libpq based clients (e.g. common application frameworks and ORMs)

备注

请注意,目前不支持将 Azure AD 令牌与 pgAdmin 结合使用,因为这对密码有 256 个字符的硬编码限制(令牌超过了该限制)。Please be aware that using the Azure AD token with pgAdmin is currently not supported, since it has a hard-coded limitation of 256 characters for passwords (which the token exceeds).

以下是用户/应用程序使用 Azure AD 进行身份验证所需的步骤:These are the steps that a user/application will need to do authenticate with Azure AD described below:

先决条件Prerequisites

请确保已安装 Azure CLIMake sure you have the Azure CLI installed.

步骤 1:使用 Azure AD 进行身份验证Step 1: Authenticate with Azure AD

首先使用 Azure CLI 工具进行 Azure AD 的身份验证。Start by authenticating with Azure AD using the Azure CLI tool.

az login

该命令将启动浏览器窗口,以显示 Azure AD 身份验证页。The command will launch a browser window to the Azure AD authentication page. 这一操作需要提供 Azure AD 的用户 ID 和密码。It requires you to give your Azure AD user ID and the password.

步骤 2:检索 Azure AD 访问令牌Step 2: Retrieve Azure AD access token

调用 Azure CLI 工具,获取步骤 1 中经过 Azure AD 身份验证的用户的访问令牌,以访问 Azure Database for PostgreSQL。Invoke the Azure CLI tool to acquire an access token for the Azure AD authenticated user from step 1 to access Azure Database for PostgreSQL.

示例:Example:

az account get-access-token --resource https://ossrdbms-aad.database.chinacloudapi.cn

上述资源值必须完全按所示方式指定。The above resource value must be specified exactly as shown. 对于其他云,可以使用以下命令查看资源值:For other clouds, the resource value can be looked up using:

az cloud show

对于 Azure CLI 版本 2.0.71 和更高版本,可以在以下更为方便的版本中为所有云指定命令:For Azure CLI version 2.0.71 and later, the command can be specified in the following more convenient version for all clouds:

az account get-access-token --resource-type oss-rdbms

身份验证成功后,Azure AD 将返回访问令牌:After authentication is successful, Azure AD will return an access token:

{
  "accessToken": "TOKEN",
  "expiresOn": "...",
  "subscription": "...",
  "tenant": "...",
  "tokenType": "Bearer"
}

该令牌是一个 Base 64 字符串,该字符串对有关经过身份验证的用户的所有信息进行编码,并且针对的是 Azure Database for PostgreSQL 服务。The token is a Base 64 string that encodes all the information about the authenticated user, and which is targeted to the Azure Database for PostgreSQL service.

备注

访问令牌的有效期介于 5 分钟到 60 分钟之间。The access token validity is anywhere between 5 minutes to 60 minutes. 建议你就在启动 Azure Database for PostgreSQL 登录之前获取访问令牌。We recommend you get the access token just before initiating the login to Azure Database for PostgreSQL.

步骤 3:使用令牌作为密码以使用 PostgreSQL 登录Step 3: Use token as password for logging in with PostgreSQL

在连接时,需要将访问令牌用作 PostgreSQL 用户密码。When connecting you need to use the access token as the PostgreSQL user password.

使用 psql 命令行客户端时,需要通过 PGPASSWORD 环境变量传递访问令牌,因为访问令牌超出了 psql 可以直接接受的密码长度:When using the psql command line client, the access token needs to be passed through the PGPASSWORD environment variable, since the access token exceeds the password length that psql can accept directly:

Windows 示例:Windows Example:

set PGPASSWORD=<copy/pasted TOKEN value from step 2>
$env:PGPASSWORD='<copy/pasted TOKEN value from step 2>'

Linux/macOS 示例:Linux/macOS Example:

export PGPASSWORD=<copy/pasted TOKEN value from step 2>

现在,你可以像往常一样使用 Azure Database for PostgreSQL 启动连接:Now you can initiate a connection with Azure Database for PostgreSQL like you normally would:

psql "host=mydb.postgres... user=user@tenant.partner.onmschina.cn@mydb dbname=postgres sslmode=require"

连接时的重要注意事项如下:Important considerations when connecting:

  • user@tenant.partner.onmschina.cn 是你尝试要以其身份连接的 Azure AD 用户或组的名称user@tenant.partner.onmschina.cn is the name of the Azure AD user or group you are trying to connect as
  • 在 Azure AD 用户/组名称的后面始终要追加服务器名称(例如 @mydbAlways append the server name after the Azure AD user/group name (e.g. @mydb)
  • 请确保使用 Azure AD 用户或组名称的确切拼写方式Make sure to use the exact way the Azure AD user or group name is spelled
  • Azure AD 的用户名和组的名称区分大小写Azure AD user and group names are case sensitive
  • 在作为组进行连接时,请只使用组名称(例如 GroupName@mydbWhen connecting as a group, use only the group name (e.g. GroupName@mydb)
  • 如果名称包含空格,请在每个空格前使用 \ 对该空格进行转义If the name contains spaces, use \ before each space to escape it

现在可以使用 Azure AD 身份验证向 PostgreSQL 服务器进行身份验证。You are now authenticated to your PostgreSQL server using Azure AD authentication.

在 Azure Database for PostgreSQL 中创建 Azure AD 用户Creating Azure AD users in Azure Database for PostgreSQL

若要向 Azure Database for PostgreSQL 数据库添加 Azure AD 用户,请在连接后执行以下步骤(请参阅后面有关如何连接的部分):To add an Azure AD user to your Azure Database for PostgreSQL database, perform the following steps after connecting (see later section on how to connect):

  1. 首先确保 Azure AD 用户 <user>@yourtenant.partner.onmschina.cn 是 Azure AD 租户中的有效用户。First ensure that the Azure AD user <user>@yourtenant.partner.onmschina.cn is a valid user in Azure AD tenant.
  2. 以 Azure AD 管理员用户身份登录到 Azure Database for PostgreSQL 实例。Sign in to your Azure Database for PostgreSQL instance as the Azure AD Admin user.
  3. 在 Azure Database for PostgreSQL 中创建角色 <user>@yourtenant.partner.onmschina.cnCreate role <user>@yourtenant.partner.onmschina.cn in Azure Database for PostgreSQL.
  4. 使 <user>@yourtenant.partner.onmschina.cn 成为角色 azure_ad_user 的成员。Make <user>@yourtenant.partner.onmschina.cn a member of role azure_ad_user. 这一定只能向 Azure AD 用户提供。This must only be given to Azure AD users.

示例:Example:

CREATE ROLE "user1@yourtenant.partner.onmschina.cn" WITH LOGIN IN ROLE azure_ad_user;

备注

通过 Azure AD 对用户进行身份验证时,不会向用户授予访问 Azure Database for PostgreSQL 数据库中的对象的任何权限。Authenticating a user through Azure AD does not give the user any permissions to access objects within the Azure Database for PostgreSQL database. 必须手动向用户授予所需的权限。You must grant the user the required permissions manually.

在 Azure Database for PostgreSQL 中创建 Azure AD 组Creating Azure AD groups in Azure Database for PostgreSQL

若要启用 Azure AD 组以访问数据库,请使用与用户相同的机制,但请指定组名称:To enable an Azure AD group for access to your database, use the same mechanism as for users, but instead specify the group name:

示例:Example:

CREATE ROLE "Prod DB Readonly" WITH LOGIN IN ROLE azure_ad_user;

登录时,组成员将使用其个人访问令牌,但使用指定为用户名的组名称进行签名。When logging in, members of the group will use their personal access tokens, but sign with the group name specified as the username.

令牌验证Token Validation

Azure Database for PostgreSQL 中的 Azure AD 身份验证确保 PostgreSQL 服务器中存在用户,并通过验证令牌的内容来检查令牌的有效性。Azure AD authentication in Azure Database for PostgreSQL ensures that the user exists in the PostgreSQL server, and it checks the validity of the token by validating the contents of the token. 执行以下令牌验证步骤:The following token validation steps are performed:

  • 令牌是否由 Azure AD 签名,并且未被篡改Token is signed by Azure AD and has not been tampered with
  • 是否由 Azure AD 为与服务器关联的租户颁发令牌Token was issued by Azure AD for the tenant associated with the server
  • 令牌尚未过期Token has not expired
  • 令牌用于 Azure Database for PostgreSQL 资源(而不是其他 Azure 资源)Token is for the Azure Database for PostgreSQL resource (and not another Azure resource)

将现有 PostgreSQL 用户迁移到基于 Azure AD 的身份验证Migrating existing PostgreSQL users to Azure AD-based authentication

可以为现有用户启用 Azure AD 身份验证。You can enable Azure AD authentication for existing users. 有两种要考虑的事例:There are two cases to consider:

事例 1:PostgreSQL 用户名与 Azure AD 用户主体名称匹配Case 1: PostgreSQL username matches the Azure AD User Principal Name

在一种不大可能出现的情况下,如果现有用户已与 Azure AD 用户名相匹配,则可以向其授予 azure_ad_user 角色,以便为其启用 Azure AD 身份验证:In the unlikely case that your existing users already match the Azure AD user names, you can grant the azure_ad_user role to them in order to enable them for Azure AD authentication:

GRANT azure_ad_user TO "existinguser@yourtenant.partner.onmschina.cn";

用户现在将可以使用 Azure AD 凭据登录,而不是使用以前配置的 PostgreSQL 用户密码。They will now be able to sign in with Azure AD credentials instead of using their previously configured PostgreSQL user password.

事例 2:PostgreSQL 用户名与 Azure AD 用户主体名称不同Case 2: PostgreSQL username is different than the Azure AD User Principal Name

如果 PostgreSQL 用户在 Azure AD 中不存在或者具有另外的用户名,则可以使用 Azure AD 组作为此 PostgreSQL 用户进行身份验证。If a PostgreSQL user either does not exist in Azure AD or has a different username, you can use Azure AD groups to authenticate as this PostgreSQL user. 可以创建一个名称与 PostgreSQL 用户匹配的 Azure AD 组,然后向现有的 PostgreSQL 用户授予角色 azure_ad_user,从而将现有 Azure Database for PostgreSQL 用户迁移到 Azure AD 中:You can migrate existing Azure Database for PostgreSQL users to Azure AD by creating an Azure AD group with a name that matches the PostgreSQL user, and then granting role azure_ad_user to the existing PostgreSQL user:

GRANT azure_ad_user TO "DBReadUser";

这假定你已在 Azure AD 中创建了组“DBReadUser”。This assumes you have created a group "DBReadUser" in your Azure AD. 属于该组的用户现在能够以此用户身份登录到数据库。Users belonging to that group will now be able to sign in to the database as this user.

后续步骤Next steps