
I had a problem with a C# Winforms application recently that uses EF and some ADO.NET code to access SQL/Server. The customer wanted to use Active Directory to set up the users for this system.
There are two ways of doing this:
- Define the AD users in SQL Server Management Studio (SSMS), assigning these to the roles that are defined in the database, e.g. User, Manager, Admin etc.
- Define the AD users and AD groups in Active Directory, and then just map the groups to roles in SSMS.
The customer wanted to use the second method and this had me confused for a bit, because it means that the users are not defined in the database, so sp_helpuser will come up with an error if you try to use it.
In the past I had used my own views to do this kind of thing but its dependant on the version of SQL/Server because my views were based on SQL/Server system views. There had to be an easier way.
What I came up with was to use sp_helprolemember and filter for the current user (in case the customer wanted to use AD users in SSMS), then use two calls, one to xp_logininfo, then pass the results to sp_helpuser. So to summarise the plan is to do something like this:
EXEC sys.sp_helprolemember @rolename = NULL -- sysname -- filter using the user id for just the roles we are interested in -- does not return anything unless you set AD users up in SSMS -- returns MyMachine\TestGroup as a group EXEC sys.xp_logininfo @acctname = 'MyMachine\phil', -- sysname @option = 'ALL' -- varchar(10) -- get the roles that the MyMachine\TestGroup is assigned to, which is what we are trying to get in the first place EXEC sys.sp_helpuser @name_in_db = 'MyMachine\TestGroup'
The above code will not work as such, its just an explanation of the approach. I’ve included the actual code I have used in the app, which is part of a C# database helper class:
public static string[] GetRolesForLoggedOnUser(string userName) { var roles = new ArrayList(); using (var con = new SqlConnection(_currentConnectionString)) { con.Open(); #if DEBUG CurrentLogger.Trace("Finding roles for user {0}", userName); #endif // find out the roles for this user string sql = "sp_helprolemember"; using (var cmd = new SqlCommand(sql, con)) { cmd.CommandType = CommandType.StoredProcedure; var rdr = cmd.ExecuteReader(); while (rdr.Read()) { var dbRole = (string)rdr["DbRole"]; var memberName = (string)rdr["MemberName"]; if (String.Equals(memberName, userName, StringComparison.OrdinalIgnoreCase)) AddRole(roles, dbRole); } rdr.Close(); }; // find out the ad groups for this user var permissionPaths = new ArrayList(); sql = "xp_logininfo"; using (var cmd = new SqlCommand(sql, con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@acctname", userName); cmd.Parameters.AddWithValue("@option", "ALL"); var rdr = cmd.ExecuteReader(); while (rdr.Read()) { if (rdr["permission path"] == DBNull.Value) continue; var permissionPath = (string)rdr["permission path"]; AddRole(roles, permissionPath); permissionPaths.Add(permissionPath); } rdr.Close(); } // now look at all those groups and see if they have anything of interest sql = "sp_helpuser"; using (var cmd = new SqlCommand(sql, con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@name_in_db", SqlDbType.VarChar); foreach (var permissionPath in permissionPaths) { cmd.Parameters["@name_in_db"].Value = permissionPath; var rdr = cmd.ExecuteReader(); while (rdr.Read()) { var roleName = (string) rdr["RoleName"]; AddRole(roles, roleName); } rdr.Close(); } } con.Close(); } return (string[])roles.ToArray(typeof(string)); } private static void AddRole(ArrayList roles, string roleToAdd) { #if DEBUG CurrentLogger.Trace("role = {0}",roleToAdd); #endif roles.Add(roleToAdd); }
I am thinking that an alternative might be just to call sp_helpuser and if an error occurs then the user doesn’t exist and seeing as we are connected to the database, then its reasonable to carry out the second and third steps above. However I’m happy with this approach. Just trying to work out if the final step needs a try/catch as I write, just in case something comes out of xp_logininfo that might ruin my day.
Update: IS_MEMBER
Since writing the original post I have come across something that might be easier for detecting SQL roles and AD groups, the T-SQL function IS_MEMBER.
This function returns 1 if the user is a member of the role, 0 if the role is valid but the user is not a member, null otherwise. The C# code then becomes:
public static string[] GetRolesForLoggedOnUserTake4(string userName) { var roles = new ArrayList(); using (var con = new SqlConnection(_currentConnectionString)) { con.Open(); const string sql = "SELECT is_member(@role)"; using (var cmd = new SqlCommand(sql, con)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@role", SqlDbType.VarChar); foreach (var role in new[]{"Role1","Role2","etc"}) { cmd.Parameters["@role"].Value = role; var result = cmd.ExecuteScalar(); if (result != DBNull.Value && result != 0) AddRole(roles, role); } } } return (string[])roles.ToArray(typeof(string)); }
If your app understands SQL roles internally, but has to be able to handle AD groups (typically so DBA’s don’t have to do anything to set up users, then some translation may be required. You could pass the total list of roles needed in as key value pairs – role name, ad group name, or role name, role name. The above code becomes:
public static string[] GetRolesForLoggedOnUserTake(string userName, IEnumerable> allRoles) { var roles = new ArrayList(); using (var con = new SqlConnection(_currentConnectionString)) { con.Open(); const string sql = "SELECT IS_MEMBER(@role)"; using (var cmd = new SqlCommand(sql, con)) { cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@role", SqlDbType.VarChar); foreach (var role in allRoles) { cmd.Parameters["@role"].Value = role.Value ?? role.Key; var result = cmd.ExecuteScalar(); if (result != DBNull.Value && (int)result == 1) AddRole(roles, role.Key); } } } return (string[])roles.ToArray(typeof(string)); }
There are also worries about the user not having a schema if defined via an AD group in versions of SQL/Server prior to 2012, which might have temporary table/processing implications. If these problems affect you, then defining the users in Active Directory and the mappings in SQL/Server management studio might be the best option (i.e. do not use Active Directory Groups).
Leave a Reply