Tip: Getting the normal domain username from the claims username in SharePoint 2013

Introduction to the problem

It’s not uncommon when upgrading to SharePoint 2013 from a previous version of SharePoint that you’ll get encoded claims usernames in the places you may have seen normal usernames (DOMAIN) syntaxes before. In my case it was a matter of finding a ton of custom code and have it check whether the username was a claims encoded username or not.

This is what we saw:
POINTBIRD\tobiaszimmergren

There’s a good reason for why the username that is claims encoded look the way it does. The format tells us what type of claim it is. Wictor has done a nice breakdown and explained the claims here: http://www.wictorwilen.se/Post/How-Claims-encoding-works-in-SharePoint-2010.aspx

The solution to this problem

There’s a pretty simple solution for this that it looks like a lot of people are missing out on. The code snippets I’ve seen in the last project are all parsing the string manually with custom logic and then trying to determine on a string.split() if it is a claim and what type of claim it is.

Instead of going down that dark and horrible road, you should take a look at the built-in functions in the API that does this just fine for us:

private string GetUsernameFromClaim(string claimsEncodedUsername)
{
    using (new SPMonitoredScope("GetUsernameFromClaim method start"))
    {
        try
        {
            SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
            if (spClaimProviderManager != null)
            {
                if (SPClaimProviderManager.IsEncodedClaim(claimsEncodedUsername))
                {
                    // return the normal domain/username without any claims identification data
                    return spClaimProviderManager.ConvertClaimToIdentifier(claimsEncodedUsername);
                }
            }
        }
        catch (Exception ex)
        {
            // You should handle any exceptions in here instead of ignoring them!
            // Logger.Log("An exception occured in the GetUsernameFromClaim() method");
            return claimsUsername; // Or just return the original username.
        }
 
        // Return the original username value if it couldn't be resolved as a claims username
        return claimsUsername;
    }
}

Summary

Since I saw so many places in the previous few projects where people have been referencing custom methods for string-splits to sort out the claims usernames into default domainformats, I thought you’d benefit from knowing that there’s a built-in method for that. Nothing fancy, but worth to know about it.

Check out these resources for additional and more in-depth information about related things:

Programmatically converting login name to claim and vice versa, by Waldek Mastykarz

How claims work in SharePoint 2010, by Wictor Wilén

Enjoy this quick tip.