存储过程作为创建表代理?

tlu*_*lum 5 security sql-server stored-procedures sql-server-2008-r2

我认为,对于 SQL Server,我认为您可以通过特定约束提升用户权限。

例如,您需要用户在特定模式中创建特定表对象。您可以将创建表包装在存储过程中并仅授予他们访问权限,而不是授予他们批发创建表权限。通过这种方式,他们将被限制为仅创建在过程中指定的对象,并且对数据库没有任何直接的创建表权限......至少我知道它可以通过选择、插入、更新、删除以这种方式工作。存储过程中的 Create Table 语句引发 Permission Denied 错误。

我是错了还是只是做错了什么?

Tho*_*ger 4

是的,它应该按照你的想法工作。下面是一个例子来证明这一点:

-- create the dummy login
create login TestLogin1
with password = 'p@$$w0rd';
go

use TestDB;
go

-- create the test user
create user TestUser1
for login TestLogin1;
go

-- create the proc to create a table
create procedure dbo.CreateTableProc
as

    create table dbo.SomeTestTable(id int);

go

-- give TestUser1 perms to execute CreateTableProc
grant execute
on dbo.CreateTableProc
to TestUser1;
go


-- execute CreateTableProc under the security context of TestUser1
execute as user = 'TestUser1';
go

exec dbo.CreateTableProc;
go

revert;
go
-- unsuccessful, permission denied
Run Code Online (Sandbox Code Playgroud)

消息 262,级别 14,状态 1,过程 CreateTableProc,第 4
行在数据库“TestDB”中拒绝创建表权限。

-- alter the proc to execute under my security context (with CREATE TABLE perms)
alter procedure dbo.CreateTableProc
    with execute as owner
as

    create table dbo.SomeTestTable(id int);

go

-- execute CreateTableProc under the security context of TestUser1
execute as user = 'TestUser1';
go

exec dbo.CreateTableProc;
go

revert;
go
-- successful, table created
Run Code Online (Sandbox Code Playgroud)

命令成功完成。

在本例中,TestUser1没有创建表的权限。CreateTableProc我们看到,当调用原始版本时, CREATE TABLEDDL 在 的安全上下文下执行TestUser1。但是,通过修改CreateTableProc存储过程定义并包含该WITH EXECUTE AS OWNER子句,现在TestUser1可以成功调用 proc 并创建表,因为现在CREATE TABLEDDL 在所有者(我的数据库用户,在角色中db_owner)的安全上下文下执行。