我有一个存储过程:S1.ProcA - S1是模式 - ProcA访问dbo模式中的表dbo.T1。
我希望user1能够通过S1.ProcA访问dbo.T1 - 我给了exec访问S1.ProcA,但是,它错误了"选择权限在dbo.T1上被拒绝...& #34;
如何通过proc S1.ProcA将user1访问表dbo.T1,而无需直接访问该表?
感谢。
答案 0 :(得分:1)
您可以使用EXECUTE AS指定在其安全上下文下运行存储过程的其他用户。
CREATE PROCEDURE your_proc
WITH EXECUTE AS 'user_with_permission_on_schema'
AS SELECT * FROM your_schema.your_table
因此,如果您的登录/用户对proc引用的对象具有适当的权限,则可以使用该登录/用户来执行存储的proc而不是调用者。
如果您想在管理控制台中使用权限,可以使用EXECUTE AS USER = 'user'
和REVERT
(返回正常登录)命令在测试时更改安全上下文。
SQL Server安全性可能是一个复杂的主题,我建议您仔细阅读documentation,因为这可能不是您想要占用太多机会的区域。
这是如何工作的一个例子:
-- create schemas, table, users, proc and grant permissions
CREATE SCHEMA demo_s1
GO
CREATE SCHEMA demo_s2
GO
CREATE USER [schema_s1_owner] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[demo_s1]
GO
CREATE USER [schema_s2_user] WITHOUT LOGIN WITH DEFAULT_SCHEMA=[demo_s2]
GO
CREATE TABLE demo_s1.your_table (column1 int)
INSERT demo_s1.your_table VALUES (1),(2),(3)
GO
GRANT SELECT ON demo_s1.your_table TO [schema_s1_owner]
GO
CREATE PROCEDURE select_from_s1_your_table
WITH EXECUTE AS 'schema_s1_owner'
AS SELECT * FROM demo_s1.your_table
GO
GRANT EXECUTE ON select_from_s1_your_table TO [schema_s2_user]
GO
-- try executing as limited user
EXECUTE AS USER = 'schema_s2_user' -- change security context
SELECT * FROM demo_s1.your_table -- this will fail with 'SELECT permission was denied'
GO
EXEC select_from_s1_your_table -- this will work and return results
GO
REVERT -- go back to the ordinary login and clean up
GO
-- clean up
DROP TABLE demo_s1.your_table
GO
DROP PROC select_from_s1_your_table
GO
DROP USER [schema_s2_user]
GO
DROP USER [schema_s1_owner]
GO
DROP SCHEMA demo_s1
GO
DROP SCHEMA demo_s2
GO