I am automating login creations on a SQL Server 2008 database using SMO in VB.NET. I have created the login, created the user in the database, given the user roles, and set the login name of the user to the login I created at the server level.
What I haven’t been able to do is get the User Mapping right. But maybe I am misunderstanding something. I am not a SQL Security guru by any means.
Sub Main()
Dim TargetServerName As String = "MyServer"
Dim TargetDBName As String = "PermissionTestDB"
Dim strGroupName As String = "TestGroup"
Dim TargetServer As New Server(TargetServerName)
Dim TargetDataBase As Database = TargetServer.Databases(TargetDBName)
' First we will create a SQL Server Login
Dim newLogin As New Login(TargetServer, String.Format("DOMAIN\{0}", strGroupName))
newLogin.LoginType = LoginType.WindowsGroup
newLogin.Create()
'Next we will create a Database User login
Dim dbLogin As New User(TargetDataBase, newLogin.Name)
TargetDataBase.Users.Add(dbLogin)
dbLogin.Login = newLogin.Name
newLogin.DefaultDatabase = TargetDBName
'Assign the Database Login some roles
Dim DataReaderServerRole As DatabaseRole = TargetDataBase.Roles("db_datareader")
Dim DataWriterServerRole As DatabaseRole = TargetDataBase.Roles("db_datawriter")
DataReaderServerRole.AddMember(dbLogin.Name)
DataWriterServerRole.AddMember(dbLogin.Name)
'And Add a permission under the dbo schema
Dim dboPermission As New ObjectPermissionSet(ObjectPermission.Alter)
TargetDataBase.Schemas("dbo").Grant(dboPermission, newLogin.Name)
'Map the Database User to the Server login
Dim dbMapping As New DatabaseMapping(newLogin.Name, TargetDBName, dbLogin.Name)
End Sub
The last line creates a mapping, and in another sub I called the EnumDatabaseMappings method and the mapping is there, however when I go into Management Studio and go to SERVER>Security>Logins>”Domain\TestGroup”>User Mappings page, the line in the list for PermissionTestDB is not checked. In the grid below, I can see that the login and associated user have the db_datareader and db_datawriter roles enabled, but it is all grayed out.
Am I going about this the wrong way? DatabaseMapping class doesn’t have very extensive documentation, so any help would be greatly appreciated.
1 Answer