MS SQL Server: Check to see if a user can execute a stored procedure

南笙酒味 提交于 2019-12-18 04:10:02

问题


How can you check to see if a user can execute a stored procedure in MS SQL server?

I can see if the user has explicit execute permissions by connecting to the master database and executing:

databasename..sp_helpprotect 'storedProcedureName', 'username'

however if the user is a member of a role that has execute permissions sp_helprotect won't help me.

Ideally I'd like to be able to call something like

databasename..sp_canexecute 'storedProcedureName', 'username'

which would return a bool.


回答1:


fn_my_permissions and HAS_PERMS_BY_NAME




回答2:


Try something like this:

CREATE PROCEDURE [dbo].[sp_canexecute]
@procedure_name varchar(255),
@username varchar(255),
@has_execute_permissions bit OUTPUT
AS

IF EXISTS (
        /* Explicit permission */
        SELECT 1
        FROM sys.database_permissions p
        INNER JOIN sys.all_objects o ON p.major_id = o.[object_id] AND o.[name] = @procedure_name
        INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND dp.[name] = @username
    )
    OR EXISTS (
        /* Role-based permission */
        SELECT 1
        FROM sys.database_permissions p
        INNER JOIN sys.all_objects o ON p.major_id = o.[object_id]
        INNER JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id AND o.[name] = @procedure_name
        INNER JOIN sys.database_role_members drm ON dp.principal_id = drm.role_principal_id
        INNER JOIN sys.database_principals dp2 ON drm.member_principal_id = dp2.principal_id AND dp2.[name] = @username
    )
BEGIN
    SET @has_execute_permissions = 1
END
ELSE
BEGIN
    SET @has_execute_permissions = 0
END
GO



回答3:


Assuming the SP only runs a SELECT statement:

EXECUTE AS USER = [User's ID/Login]
EXEC sp_foobar( sna, fu)
REVERT

It's important to note that you will need to run the REVERT command after the prompt as SQL Server will regard you as the user you are EXECUTING AS until you either shut down the connection or REVERT the impersonation. That said, you should see exactly what a user would get (getting some rows but not all? This should help you out).



来源:https://stackoverflow.com/questions/484145/ms-sql-server-check-to-see-if-a-user-can-execute-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!