1

我希望 SQL Server 权限符合我在连接字符串中指定的 ID,而不是那些碰巧正在运行 PowerShell 脚本的人(通常是我)。

例如,我有一个名为“MyTable”的表,我可以更新它,但“TestIDRestricted”不能。

我以“TestIDRestricted”身份登录 Microsoft SQL Server Management Studio 并运行以下查询

select MyField
from MyTable
where ID = 2

我看到它返回“4”。我现在尝试更新:

update MyTable
set MyField = 5
where ID = 2

正如预期的那样,我得到以下失败结果:

Msg 229, Level 14, State 5, Line 1
The UPDATE permission was denied on the object 'MyTable', database 'mydb', schema 'dbo'.

接下来,我运行以下 UpdateProblem.ps1 PowerShell 脚本:

$ConnectionString = "Server=MyServer\MSSQL2012;Database=mydb;User Id= TestIDRestricted;Password=secretpasswd;"
$ConnectionString = $ConnectionString + "Trusted_Connection = yes;Persist Security Info=False"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $ConnectionString
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()
$updateSQL ="update MyTable set MyField = 5 where ID = 2"
$sqlCommand.CommandText = $updateSQL 
write-host $updateSQL
#following command should fail
$sqlCommand.ExecuteNonQuery()
$sqlConnection.close() 

我预计此更新会失败,因为我没有在连接字符串中指定集成安全性。但是,当我以“TestIDRestricted”身份重新登录 Microsoft SQL Server Management Studio 并再次运行以下查询时

select MyField
from MyTable
where ID = 2

我看到它返回“5”。因此,即使我预计它会失败,更新也成功了。据我所知,它成功的原因是因为 SQL 权限基于我的 ID,使用集成安全性,而不是与我在连接字符串中使用的 ID 关联的安全性。

如何让脚本使用与我在连接字符串中指定的 ID 关联的权限,而不是使用我的 ID 的权限,这些权限似乎遵循集成安全性?

4

2 回答 2

1

您将 Trusted_Connection 设置为 TRUE;这几乎可以肯定意味着您正在使用当前用户的凭据进行连接,而不是连接字符串中指定的凭据。尝试:

$ConnectionString = "Server=MyServer\MSSQL2012;Database=mydb;User Id= TestIDRestricted;Password=secretpasswd;"
$ConnectionString = $ConnectionString + "Trusted_Connection = no;Persist Security Info=False"
于 2013-04-10T20:50:05.750 回答
0

您可能只需注释掉第二行:

$ConnectionString = "Server=MyServer\MSSQL2012;Database=mydb;User Id= TestIDRestricted;Password=secretpasswd;"
' $ConnectionString = $ConnectionString + "Trusted_Connection = yes;Persist Security Info=False"

(这是VB吗?)

于 2013-04-10T20:55:13.527 回答