连接到 Azure SQL 数据库 AAD 的 Azure Pipelines - 用户“< token 识别的主体>”登录失败

标签 azure azure-devops azure-sql-database

我正在尝试使用 AAD 帐户连接到 Azure SQL DB,作为我的 Azure 管道的一部分。我大致有以下内容:

具有关联服务连接的 Azure 管道。 Azure SQL DB,其中 AAD 管理员设置为(连接的)服务主体。 获取服务主体的不记名 token 的 Azure CLI 任务。

然后,我有一个 Azure Powershell 脚本,它使用不记名 token 连接到数据库:

$conn = new-object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=tcp:$($sqlServer),1433;Initial Catalog=$($sqlDB);Persist Security Info=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" 
$conn.AccessToken = $env:ACCESSTOKEN
$conn.Open()

这会导致以下错误:

Login failed for user '<token-identified principal>

允许运行管道的代理通过 SQL Server 防火墙。

在数据库日志中,错误代码为 18456,状态为 132(AAD 失败)。

我已经使用 Azure CLI 手动测试了这一点,使用服务连接服务主体登录,请求不记名 token ,然后连接到数据库(使用上面的代码),这有效。

如果我比较 Pipeline 测试和 Azure CLi 手动测试的不记名 token ,它们是相同的(除了 exp、uti 和 aio)

有什么想法吗?

最佳答案

根据this doc :

This authentication method allows middle-tier services to obtain JSON Web Tokens (JWT)

您需要使用id_token用于 Azure AD 身份验证。从您的脚本来看,您似乎正在使用管道环境访问 token 。

另一方面,您可以导航到Azure Portal -> Azure Sql -> Query Editor页面。 然后您可以选择Active Directory authentication并检查是否可以成功登录数据库。

Azure Sql

如果您遇到问题Login failed for user '<token-identified principal>在此页面中, 您可以尝试将目标帐户添加为 Active Directory admin在 SQL Server 上或 create contained users mapped to Azure AD identities .

AAD admin

此外,您还可以使用Azure AD帐户和密码登录Azure SQL。

脚本:

$conn = new-object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Server=tcp:$($sqlServer),1433;Initial Catalog=$($sqlDB);Persist Security Info=False;User ID:User account;Password=Password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication=Active Directory Password;" 
$conn.Open()

更新:

对于访问 token :

您可以尝试在 Azure Cloud shell 中运行 Azure CLI 命令:

az login

az account get-access-token --resource https://database.windows.net

然后您就可以获得访问 token 。

Access token

根据我的测试,如果您使用此访问 token 连接 Azure Sql ,它可以按预期工作。

更新2:

得到它。如果您将服务主体设置为 AD 管理员。 手动服务主体类型服务连接可以工作。

Manual

例如:

- task: AzureCLI@2
  displayName: 'Azure CLI '
  inputs:
    azureSubscription: manual service connection name
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
     
     az account get-access-token --resource https://database.windows.net
  enabled: false

访问 token 可用于连接 Azure Sql。

关于连接到 Azure SQL 数据库 AAD 的 Azure Pipelines - 用户“< token 识别的主体>”登录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62534128/

相关文章:

git push --mirror 自动添加指向不正确工作项的链接

powershell - 在 Azure-Pipelines.yml 中使用 AzureFileCopy 任务输出

azure 自动化: 'Invoke-ProcessASDatabase' is not recognized

c# - WCF 用户名身份验证 - 教程中的异常

azure - 向 Azure 认知 API 发送批量请求以进行 TEXT-OCR

azure-devops - 我的公共(public)项目 Microsoft 托管 0 个并行作业

azure - Team Foundation Service 托管的构建 Controller 位于哪个子区域?

剩下的交给 Azure SQL 数据库集成服务

Azure B2C 自定义策略和客户端 ID

本地和生产的 Azure ACS 配置