Introduction
It's a very common problem we developers encounter when we upgrade our solution from a previous version of SharePoint to the latest 2013 version when you get encoded claims usernames (in other words i:0#.w|DOMAIN\USERNAME name instead of DOMAIN\USERNAME).
When executing the code this is what we get for the username value: i:0#.w|DOMAIN\USERNAME but to output our code we need something like DOMAIN\USERNAME.
Some Information Related to the Problem
However why does the username that is claims encoded look the way it does? Some way it helps us since the claims format tells us what type of claim it is. If you still want to see the provider settings you can see it by selecting Web Application in Central Administration.Navigate to the path shown below:
Application Management -> Manage Web Application -> Select your Web App - > In Ribbon Select Authentication Provider.
There you will see the current authentication provider for the web application you selected.
Solution
When searching for a solution I have seen it in many places where people are using methods like string-splits to eliminate the claims usernames and convert it to the default domain\username format. Hopefully the method below might save someone hours of work.
Please find the following code snippet that will satisfy your purpose.
-
-
-
-
-
- public static string GetUsernameFromClaim(string claimsEncodedUsername, SPUser spUser)
- {
- string claimsUsername = claimsEncodedUsername;
- try
- {
- SPClaimProviderManager spClaimProviderManager = SPClaimProviderManager.Local;
- if (spClaimProviderManager != null)
- {
- if (spUser != null)
- {
- SPClaim userClaim = spClaimProviderManager.ConvertSPUserToClaim(spUser);
- return spClaimProviderManager.ConvertClaimToIdentifier(userClaim.ToEncodedString());
- }
- }
- }
- catch (Exception ex)
- {
-
- return claimsUsername;
- }
-
- return claimsUsername;
- }
This is how you need to call the method:
GetUsernameFromClaim("i:0#.w|DOMAIN\USERNAME",spUser)
Rather than going for methods like String.Split() or others, we should go for something that is using OOB functions in the SharePoint API.
Happy SharePoint !!!!