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",
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.
Good work on including a PowerShell example in addition to C#!
Thank you for adding the powershell script as well. Very helpful and Much appreciated!
Excellent point, Steve! Thanks.