Configure security permissions for site via code
-
02-01-2021 - |
Question
In MOSS 2007, I used to use the following code to configure security permissions on a site (also created via code):
/*Line 1*/rootWeb.CreateDefaultAssociatedGroups("CONTOSO\\SiteAdmin", "", "");
rootWeb.Update();
//----
// Add an admin domain security group to the Owners Group - FULL Access
//----
SPGroup SPOwnersGroup = site.RootWeb.AssociatedOwnerGroup;
/*Line 2*/SPUser ownerUsersByGroup = site.RootWeb.EnsureUser("CONTOSO\\SiteOwnersAccessGroup");
SPOwnersGroup.AddUser(ownerUsersByGroup);
// Add a contributor-level type domain security group the the Members Group - Contribute Access
SPGroup SPMembersGroup = site.RootWeb.AssociatedMemberGroup;
SPUser memberUsersByGroup = site.RootWeb.EnsureUser("CONTOSO\\SiteMembersAccessGroup");
SPMembersGroup.AddUser(memberUsersByGroup);
The above code is not working, and I think it has something to do with claims. If I change the Line 1
to:
rootWeb.CreateDefaultAssociatedGroups("i:0#.w|CONTOSO\\SiteAdmin", "", "");
... the code moves on and fails at Line 2
. CONTOSO\SiteOwnersAccessGroup
is an AD security group. How do I go about adding specific users and AD security groups to the permissions groups of the site, without having to hard-code the claims format (which I am unfamiliar with)?
La solution
First, You can convert the loginname to calim using the below code
string userClaimsLoginName = "";
string userLoginNameWithDomain = @"mydomain\myuser";
string xmlTypeForString = "http://www.w3.org/2001/XMLSchema#string";
// This will depend on your own implementation
string originalIssuer = SPOriginalIssuers.Format(SPOriginalIssuerType.Windows);
SPClaimProviderManager mgr = SPClaimProviderManager.Local;
if (mgr != null)
{
SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, userLoginNameWithDomain, xmlTypeForString, originalIssuer);
userClaimsLoginName = mgr.EncodeClaim(claim);
}
the output
i:0#.w|mydomain\myuser
Ref: Convert SharePoint login name to claims format and back using C#
Second, the below code would help you to add AD groupto your site
SPRoleDefinitionCollection roleDefinitions = newWeb.RoleDefinitions;
SPRoleAssignmentCollection roleAssignments = newWeb.RoleAssignments;
SPUser newUser = newWeb.EnsureUser("AD group");
newWeb.AllowUnsafeUpdates = true;
SPRoleAssignment roleAssignment = new SPRoleAssignment(newUser);
SPRoleDefinitionBindingCollection roleDefBindings = roleAssignment.RoleDefinitionBindings;
roleDefBindings.Add(roleDefinitions["Read"]);
roleAssignments.Add(roleAssignment);
newWeb.AllowUnsafeUpdates = false;
Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange