Tuesday, April 24, 2012

How to add a Windows account to Security Group in a claims based SharePoint 2010 environment

In a timer job I added users to a certain SPGroup and added this group to some libraries with contribute rights. When I logged is with that user account it didn’t have the contribute rights. The problem was that the Windows account was added instead of the claims based user.

At first I just used the following code:

   1: String loginName = "SP2010\user1";
   2: SPGroup group = web.SiteGroups["somegroup"];
   3:  
   4: SPUser user = web.EnsureUser(loginName);
   5: if (user != null)
   6: {
   7:   group.AddUser(user);
   8: }

However this added a user as formatted in this XML:

<User ID="442" Sid="S-1-5-21-4190988674-4107964418-2216591577-1137" Name="Some name" LoginName="SP2010\user1" Email="test@test.com" Notes="" IsSiteAdmin="False" IsDomainGroup="False" Flags="0" />

I changed it to look for the correct SPUser using this code snippet:
   1: String loginName = "SP2010\user1";
   2:  
   3: SPClaimProviderManager mgr = SPClaimProviderManager.Local;
   4: if (mgr != null)
   5: {
   6:   SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, loginName, "http://www.w3.org/2001/XMLSchema#string", SPOriginalIssuers.Format(SPOriginalIssuerType.Windows));
   7:   claimLoginName = mgr.EncodeClaim(claim);
   8: }
   9:  
  10:  
  11: SPGroup group = web.SiteGroups["somegroup"];
  12: SPUser user = web.EnsureUser(claimLoginName);
  13: if (user != null)
  14: {
  15:   group.AddUser(user);
  16: }

This will generate a claim that represents the windows account “SP2010\user1”. This will find the correct SPUser, the XML is:

<User ID="255" Sid="" Name="Some name" LoginName="i:0#.w|SP2010\user1" Email="test@test.com" Notes="" IsSiteAdmin="False" IsDomainGroup="False" Flags="0" />

Notice the formatting of the LoginName.

Now the correct user account (in claims format) is added to the library with contribute rights the user logging in with SP2010\user1 can contribute.

No comments:

Post a Comment