REVERT权限切换

复制代码
首先,我们登录到SQL Server.其中,有一个是具有很小权限的普通用户,另一个是系统管理员角色中的一个成员。

USE master
GO
--Add Windows logins to SQL Server
IF NOT EXISTS (SELECT * FROM sys.syslogins WHERE name = 'PC-201102041156\qanholas')
CREATE LOGIN [PC-201102041156\qanholas]
FROM WINDOWS
WITH DEFAULT_DATABASE = qanholas
IF NOT EXISTS (SELECT * FROM sys.syslogins WHERE name = 'PC-201102041156\DBA')
CREATE LOGIN [PC-201102041156\DBA]
FROM WINDOWS
WITH DEFAULT_DATABASE = qanholas



USE qanholas
--Add the new logins to the AdventureWorks database
CREATE USER qanholas FOR LOGIN [PC-201102041156\qanholas]
CREATE USER dba FOR LOGIN [PC-201102041156\DBA]
--Add SQLDBA Windows account to the db_owner role
EXEC sp_addrolemember 'db_owner', 'dba'
GO




--Create procedure that executes a SELECT with a BACKUP DATABASE command
CREATE PROCEDURE dbo.DisplayContextwithRevert
WITH EXECUTE AS CALLER
AS
--The user will only be granted permission to do this section of the code
SELECT * FROM ip
--We will just display the execution context of the user executing this section of the code for demonstration
SELECT CURRENT_USER AS UserName;
--We will switch execution context to a more privileged user to do this portion of the code
EXECUTE AS USER='dba';
BACKUP DATABASE qanholas TO DISK='C:\qanholas.BAK' WITH INIT, STATS=10;
--We will just display the execution context of the user executing this section of the code
SELECT CURRENT_USER AS UserName;
--We will revert to the execution context of the original caller to limit the privileges back
REVERT;
SELECT * FROM ip
SELECT CURRENT_USER AS UserName;
GO



USE qanholas;


GRANT EXECUTE ON dbo.DisplayContextwithRevert TO qanholas
GRANT SELECT ON ip TO qanholas
GO
-- Grant the IMPERSONATE permission on the SQLUser1 user so it can switch execution context to SQLDBA
GRANT IMPERSONATE ON USER:: dba TO qanholas
复制代码

posted @   qanholas  阅读(304)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
点击右上角即可分享
微信分享提示