我需要使用哈希密码编写应用程序角色脚本,以便将其从一个数据库复制到另一个数据库。
请考虑以下示例代码,该代码使用应用程序角色为非信任用户提供提升的访问权限:
USE tempdb;
CREATE LOGIN LimitedLogin
WITH PASSWORD = 'Password1'
, CHECK_POLICY = OFF
, CHECK_EXPIRATION = OFF;
CREATE USER LimitedLogin
FOR LOGIN LimitedLogin
WITH DEFAULT_SCHEMA = dbo;
CREATE APPLICATION ROLE MyAppRole
WITH PASSWORD = 'Password2'
, DEFAULT_SCHEMA = dbo;
EXEC sp_addrolemember @rolename = 'db_datareader'
, @membername = 'MyAppRole';
CREATE TABLE dbo.Numbers
(
[Number] int CONSTRAINT PK_Numbers
PRIMARY KEY CLUSTERED
IDENTITY(1,1) NOT NULL
);
INSERT INTO dbo.Numbers
VALUES (1)
, (2);
GO
在tempdb中创建测试设置后,我们可以以[LimitedLogin]
用户身份登录并运行以下命令:
-- login as [LimitedLogin]
USE tempdb;
SELECT *
FROM dbo.Numbers;
按预期返回以下错误:
Msg 229, Level 14, State 5, Line 1
The SELECT permission was denied on the object 'Numbers'
, database 'Test', schema 'dbo'.
但是,一旦sp_setapprole
使用适当的密码执行了,就可以从dbo.Numbers
表中看到所需的结果:
DECLARE @cookie VARBINARY(8000);
EXEC sp_setapprole @rolename = 'MyAppRole'
, @password = 'Password2'
, @fCreateCookie = 1
, @cookie = @cookie OUT;
SELECT @cookie;
SELECT TOP(10) *
FROM dbo.Numbers;
EXEC sp_unsetapprole @cookie = @cookie;
我希望能够通过从源数据库编写脚本以将其应用于目标数据库来自动创建应用程序角色。我可以通过以下方式轻松执行大部分操作:
SELECT 'CREATE APPLICATION ROLE ' + QUOTENAME(dp.name) + '
WITH PASSWORD = ''xxxx''
, DEFAULT_SCHEMA = ' + QUOTENAME(dp.default_schema_name) + ';'
FROM sys.database_principals dp
WHERE dp.type_desc = 'APPLICATION_ROLE';
但是,我真的很希望能够在脚本中使用哈希密码,例如:
CREATE APPLICATION ROLE [MyAppRole]
WITH PASSWORD = 0x12345678 HASHED
, DEFAULT_SCHEMA = [dbo];
这可能吗?大概是应用程序角色密码的哈希版本存储在数据库中的某个位置。
使用SQL Server Management Studio的“脚本到->”功能,可以使用新密码对应用程序角色进行脚本编写,如下所示:
/****** Object: ApplicationRole [MyAppRole] Script Date: 9/22/2015 10:18:12 AM ******/
/* To avoid disclosure of passwords, the password is generated in script. */
declare @idx as int
declare @randomPwd as nvarchar(64)
declare @rnd as float
select @idx = 0
select @randomPwd = N''
select @rnd = rand((@@CPU_BUSY % 100) + ((@@IDLE % 100) * 100) +
(DATEPART(ss, GETDATE()) * 10000) + ((cast(DATEPART(ms, GETDATE()) as int) % 100) * 1000000))
while @idx < 64
begin
select @randomPwd = @randomPwd + char((cast((@rnd * 83) as int) + 43))
select @idx = @idx + 1
select @rnd = rand()
end
declare @statement nvarchar(4000)
select @statement = N'CREATE APPLICATION ROLE [MyAppRole] WITH DEFAULT_SCHEMA = [dbo], ' + N'PASSWORD = N' + QUOTENAME(@randomPwd,'''')
EXEC dbo.sp_executesql @statement
GO
显然,尽管这确实提供了一种生成随机密码的有趣方法,但对我而言这没有帮助。
根据到目前为止的答案,我创建了一个Connect建议,以对此产品添加支持: