Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the effective permissions for a user of a SQL Server database through C#?

When I say effective permissions, I'm referring to the permissions listed when you go into the properties of a database in SQL Server Management Studio, click "Permissions", and then click the "Effective" tab.

So far, I have been able to determine the explicit permissions with the following code:

using Microsoft.SqlServer.Management.Smo;
...
DatabasePermissionInfo[] permissions = database.EnumDatabasePermissions("username");

However, I still need to obtain the effective permissions. In this scenario, I added a login for a user and gave it the role of db_datareader and db_datawriter for a database through the User Mapping.

In the permissions for the database, the effective permissions listed are CONNECT, DELETE, INSERT, SELECT, and UPDATE, but the explicit permissions only list connect (which is the only thing that the above code pulls back). So is there a way to programmatically retrieve the effective permissions as well?

Thanks.

like image 316
athom Avatar asked Oct 08 '12 20:10

athom


People also ask

How do I check permissions on SQL Server?

Using SQL Server management studio:In the object explorer window, right click on the view and click on Properties. Navigate to the Permissions tab. Here you can see the list of users or roles who has access to the view.

Where can I find user roles and privileges in SQL Server?

To start with, server-level settings, such as server roles, permissions, user credentials and dependencies are stored in the master database. Using the server_principals system view, you can see data for all the types of server principals: S = SQL login. U = Windows login.

How do I get list of logins and permissions in SQL Server?

First, move to “Object Explorer” and expand the database that you want. Next, under the database, expand the “Security” directory. Now, under Security, expand the “Users” option. This will display a list that contains all the users created in that database.


1 Answers

I believe you can call sys.fn_my_permissions:

execute as user = 'SomeUserName' -- Set this to the user name you wish to check
select * from fn_my_permissions(null, 'DATABASE') -- Leave these arguments, don't change to MyDatabaseName
order by subentity_name, permission_name
revert

This gave me the same results as the SSMS option you mentioned.

like image 155
Tim Lehner Avatar answered Sep 19 '22 01:09

Tim Lehner