怎样给某一用户创建视图的最小权限

时间:2022-08-18 15:30:41

问题:

今天群里有位同学提问:我怎样可以给某一用户在dbo架构中创建视图的最小权限?

-------------------------------------------------------------------------------------------

第一想法很简单无非是:

CREATE ROLE MyRole; 
GO 
GRANT CREATE VIEW TO MyRole; 
GO 
CREATE USER MyUser WITHOUT LOGIN; 
GO
EXEC sp_addrolemember 'MyRole', 'MyUser'; 
GO
EXECUTE AS USER = 'MyUser'; 
GO
CREATE VIEW dbo.V_TEST
AS
SELECT 1 AA
GO
REVERT
GO

但事实是,如果仅仅这样授权,该用户会收到这样的错误信息:
消息 2760,级别 16,状态 1,过程 V_TEST,第 9 行
The specified schema name "dbo" either does not exist or you do not have permission to use it.

错误的原因是该用户没有修改架构的权限.于是添加修改dbo架构的授权:

GRANT ALTER ON SCHEMA::dbo TO MyRole;
GO
CREATE VIEW dbo.V_TEST
AS
SELECT 1 AA
GO
REVERT
GO

这次创建视图执行成功了.
但新的问题来了.由于用户拥有了修改dbo架构的权限,用户也就有了修改表/视图/存储过程/函数等的权限

,甚至拥有了删除这些对象的权限,通过刚才的授权,下面的语句就能执行成功:

EXECUTE AS USER = 'MyUser'; 
GO 
ALTER TABLE dbo.MyTable 
ADD AnotherID INT NULL; 
GO 
REVERT; 
GO   

EXECUTE AS USER = 'MyUser'; 
GO 
DROP TABLE dbo.MyTable; 
GO 
REVERT; 
GO 

要命的是,我们不能简单通过授权来禁止用户在某一架构下所有对象的删除和修改权限。

-------------------------------------------------------------------------------------------

最终解决方案:使用数据库级别的DDL触发器来取消某一角色用户的删除/修改相关对象的事物。

CREATE TRIGGER [trig_db_BlockDropObjcect]
ON DATABASE 
FOR  DROP_TABLE,DROP_VIEW,DROP_PROCEDURE,DROP_FUNCTION,DROP_CONTRACT,DROP_DEFAULT,DROP_SYNONYM,DROP_TYPE
    ,ALTER_TABLE,ALTER_PROCEDURE,ALTER_FUNCTION
AS 
BEGIN 
   IF IS_MEMBER('MyRole') = 1 
   BEGIN 
       PRINT 'You are not authorized to alter or drop this object.'; 
    --仅保留修改视图权限
ROLLBACK TRANSACTION; END; END;