使用在 Azure 中使用 MFA 的帐户调用 Sqlcmd

Posted

技术标签:

【中文标题】使用在 Azure 中使用 MFA 的帐户调用 Sqlcmd【英文标题】:Invoke-Sqlcmd with account that uses MFA in Azure 【发布时间】:2019-12-11 12:02:07 【问题描述】:

你们中的任何人都知道使用 PowerShell 和已启用 MFA 的 Azure AD 帐户执行 SQL 命令的选项吗?什么是替代方案?我需要为此创建服务主体吗?

我没有运气,但只找到了这个 cmdlet, Add-SqlAzureAuthenticationContext 但是当我尝试运行 Invoke-Sqlcmd 时,出现以下错误:

Invoke-Sqlcmd : 目标主体名称不正确。不能 生成 SSPI 上下文。

【问题讨论】:

也在找一个如何使用的例子 【参考方案1】:

要使用 AAD 凭据(无论是否为 mfa)连接到 azure 数据库,您需要为 -AccessToken 参数提供经过身份验证的用户或服务主体的令牌。

以这个为例。

使用访问令牌连接到 Azure SQL 数据库


# Obtain the Access Token: this will bring up the login dialog
Connect-AzAccount -TenantId 'Tenant where your server is'

#AZ Module
 $AccessToken = Get-AzAccessToken -ResourceUrl https://database.windows.net).Token

 $SQLInfos = @
    ServerInstance = 'SERVERNAME.database.windows.net'
    Database = 'DBNAME'
    AccessToken = $AccessToken


Invoke-Sqlcmd @SQLInfos -Query 'select * from sys.tables'

如果您不需要或不希望手动输入凭据,您可以使用配置为正确访问服务器/数据库的服务主体,并使用它来获取您的令牌。

使用服务主体客户端 ID/秘密获取访问令牌

$clientid = "enter application id that corresponds to the Service Principal" # Do not confuse with its display name
$tenantid = "enter the tenant ID of the Service Principal"
$secret = "enter the secret associated with the Service Principal"

$request = Invoke-RestMethod -Method POST `
           -Uri "https://login.microsoftonline.com/$tenantid/oauth2/token"`
           -Body @ resource="https://database.windows.net/"; grant_type="client_credentials"; client_id=$clientid; client_secret=$secret `
           -ContentType "application/x-www-form-urlencoded"
$AccessToken = $request.access_token

参考文献

MSdoc - Invoke-Sqlcmd

SecretManagement / SecretStore modules

(第二个链接没有直接关系,但如果您使用客户端 ID/秘密路线,请考虑将您的凭据存储在秘密保险库中,而不是直接存储在您的脚本中。)

【讨论】:

【参考方案2】:

不是一个真正的答案。

尝试了以下

    Add-SqlAzureAuthenticationContext -Interactive
    $sql = 'SELECT @@SERVERNAME AS ServerName';   
    $ConnectionString = 'Data Source=tcp:azSERVER.database.windows.net,1433;Initial Catalog=DBNAME;Authentication="Active Directory Interactive";User ID=USERXX@DOMAINYY.COM'
    Invoke-Sqlcmd -ConnectionString $ConnectionString -Query $sql -Verbose

得到了

Invoke-Sqlcmd:出现一个或多个错误。 在 line:4 char:5

请注意我想使用interactive 标志,

【讨论】:

以上是关于使用在 Azure 中使用 MFA 的帐户调用 Sqlcmd的主要内容,如果未能解决你的问题,请参考以下文章

使用 MFA 登录到 Azure CLI

是否可以通过 Visual Studio 将 Azure AD 与 MFA 连接起来进行实体框架调用?

[Azure - Security] Azure的多重身份验证:使用AD(Azure Active Directory)开启用户MFA

如何为某些应用程序配置 MFA(在 Azure B2C 中)每天强制执行一次(而不是每次登录时)?

Azure实践系列 4:启用和配置免费的MFA

您能否以编程方式获取 AWS MFA 序列号?