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

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

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

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

【问题讨论】:

  • 也在找一个如何使用的例子

标签: azure-sql-server invoke-sqlcmd multi-factor-authentication


【解决方案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 标志,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多