Share-n-dipity

SharePoint serendipity is the effect by which one accidentally discovers something fortunate, especially while looking for something else entirely. In this case, it is the occassional musings, observations, and Ouija board readings about the phabulously

What You Need to Know About Using EnsureUser In Claims-Based Web Apps in SharePoint 2010 and SharePoint 2013

What You Need to Know About Using EnsureUser In Claims-Based Web Apps in SharePoint 2010 and SharePoint 2013

  • Comments 4
  • Likes

We ran across an interesting wrinkle in some code last week where someone was using the EnsureUser API, which is a method off of the SPWeb.  Yes, we are talking about full trust code again, something which we haven't talked about as much lately but which still has a role in certain circumstances in SharePoint 2013 and which had a major role in SharePoint 2010.  This scenario has to do with calling EnsureUser for Windows claims users.  The key to understand here is that you should NOT be passing in the user name in the format domain\username when you are using a claims-based web application.  If you are only using Windows claims on the zone then the call will likely succeed when you pass in domain\username.  However if you add other authentication types like FBA or SAML, then this call will typically fail with a "user not found" error.

To be safe, you need to get the encoded claim value for the user and pass that into the EnsureUser method.  Here's an example of how you would do that doing full trust code:        

SPClaimProviderManager cpm = SPClaimProviderManager.Local;

SPClaim userClaim = cpm.ConvertIdentifierToClaim("domain\\username",

SPIdentifierTypes.WindowsSamAccountName);

using (SPSite theSite = newSPSite("https://www.contoso.com"))

{

     SPWeb theWeb = theSite.OpenWeb();

     SPUser theUser = theWeb.EnsureUser(userClaim.ToEncodedString());

}

If you wanted to do this in PowerShell, it would look something like this:

$claim = New-SPClaimsPrincipal -Identity corp\servero -IdentityType WindowsSamAccountName
$web.EnsureUser($claim.ToEncodedString());

The ToEncodedString() method returns a value like this:  i:0#.w|domain\\username

It's very important you follow this advice, or you will in all likelihood end up in a broken state when your code is used on a zone with more than one authentication method.

Comments
Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment