Getting Active Directory UserId from Windows Claim in SharePoint 2013

We’ve always used NTLM for our SharePoint authentication but in SharePoint 2013, claims is the preferred authentication method.  Fortunately, SharePoint 2013 ships with something called Windows Claims.  This seems to work the same as the NTLM auth from before but that windows auth is converted into a claim that SharePoint can use.

This change means that your userid would look something like this:

i:0#.w|contoso\chris

instead of this:

contoso\chris

Sometimes when calling other services, you need the windows userid and not the claim userid.  So for these instances, I’ve created a few helper methods.

//Regex needs more testing
public const string CLAIMS_REGEX = @"(?<IdentityClaim>[ic])?:?0(?<ClaimType>.)(?<ClaimValueType>.)(?<AuthMode>[wstmrfc])(\|(?<OriginalIssuer>[^\|]*))?(\|(?<ClaimValue>.*))";
 
public static string GetAdUserIdForClaim(string login)
{
    string userName = login;
 
    foreach (Match m in Regex.Matches(login, CLAIMS_REGEX, RegexOptions.IgnoreCase))
	{
		try
		{
			if (m.Groups["AuthMode"].Captures[0].Value.ToLower() == "w")
			{
				userName = m.Groups["ClaimValue"].Captures[0].Value;
			}
		}
		catch { }
	}
    return userName;
}
 
public static string GetClaimForAdUserId(string login)
{
    string userName = login;
    SPClaimProviderManager mgr = SPClaimProviderManager.Local;
    if (mgr == null) return userName;
 
    SPClaim claim = new SPClaim(SPClaimTypes.UserLogonName, login, "http://www.w3.org/2001/XMLSchema#string", SPOriginalIssuers.Format(SPOriginalIssuerType.Windows));
    userName = mgr.EncodeClaim(claim);
 
    return userName;
}
 
public static bool IsLoginClaims(string login)
{
    Regex re = new Regex(CLAIMS_REGEX, RegexOptions.IgnoreCase);
    return re.IsMatch(login);
}

First I made a regular expression to identify the different pieces of a claim (see http://social.technet.microsoft.com/wiki/contents/articles/13921.sharepoint-2013-and-sharepoint-2010-claims-encoding.aspx).  This allows me to effectively parse the claim for the windows login name (see GetAdUserIdForClaim).  This also allows me to validate whether a string is a claim or not (see IsLoginClaims).

Update 01-22-2015:

After some more usage, I found that I was being too limiting in the Claim Types and Claim Value Types in my regex.  I had based the options from the technet article above but I then ran into some other Claim Types when doing some work recently that were not in that article.  I then found this page:  http://blogs.msdn.com/b/scicoria/archive/2011/06/30/identity-claims-encoding-for-sharepoint.aspx which listed a lot more than the technet article.  It also now seems that almost any value could be there in the future.  Because of this I changed the regex in the code above to allow any value in those two fields.