The right way to find a SPUser in SharePoint 2013

Posted on 6/2/2013 @ 4:16 AM in #SharePoint by | Feedback | 7096 views

Obvious stuff out of the way, SharePoint 2013 is claims and claims only. If you’re still pimping classic windows identities, you’re a fool.

But this creates an interesting wrinkle. How the hell is one supposed to find a SPUser? This, especially given that a user id now looks like this -


.. all of those have a meaning ..

  1. i stands for identity
  2. 0 is the zero’th registered claims provider
  3. w before the pipe is windows
  4. and after pipe is the final username.

What if I had a hotmail account called ws\administrator? You see, browsing through web.SiteUsers, is no longer enough. Not only is it error prone, it won’t work for any other identity type besides Windows.

So what is a poor SharePoint developer to do? Easy. Use the cod below instead,

   1:  SPClaimProviderManager cpm = SPClaimProviderManager.Local;
   2:  SPClaim userClaim = cpm.ConvertIdentifierToClaim("ws\\administrator",SPIdentifierTypes.WindowsSamAccountName);
   3:  Console.WriteLine(userClaim.ToEncodedString());
   4:  using (SPSite site = new SPSite("http://sp"))
   5:  {
   6:      SPUser foundUser = site.RootWeb.EnsureUser(userClaim.ToEncodedString());
   7:  }

The above code, will reliably find the user for you, and you don’t have to worry about string formatting the user id. Yuck!

The SPIdentifierTypes enumeration is part of the SharePoint API and looks like as below,

   1:  namespace Microsoft.SharePoint.Administration.Claims
   2:  {
   3:      [Flags]
   4:      public enum SPIdentifierTypes
   5:      {
   6:          WindowsSamAccountName = 1,
   7:          WindowsSecurityGroupName = 2,
   8:          WindowsSecurityGroupSid = 3,
   9:          FormsUser = 4,
  10:          FormsRole = 5,
  11:          EncodedClaim = 6,
  12:      }
  13:  }

Even though 13 lines is omniously unlucky, it does have an EncodedClaim catch all for all your scenarios such as Azure AD/ACS etc. Enjoy!

Sound off but keep it civil:

Older comments..