Skip to main content

Get the login name of the current user in SharePoint 2013


Recently in one of my project, I wanted to retrieve the logged in user’s login name in the format of domain\username. This seems simple and to retrieve the username, I used the below code.
SPContext.Current.Web.CurrentUser.LoginName
But the output I received contains some extra stuff along with my domain name and username. My domain name is sp1013domain and user name is spsetup, see the output that generated by the above line of code.
i:0#.w|sp2013domain\spsetup
While searching over web, I found some guys speaking about retrieving the domain\username by splitting the above result by pipe (|) symbol, I was not convinced with that. The extra characters added to the login name is by the claims authentication, so definitely we should be able to retrieve it automated. There is a SPClaimProviderManager class that is responsible for management of various claim providers in the SharePoint farm, and there is a DecodeClaim method, that decodes a claim from an encoded string, and for my requirement these are useful to retrieve the required information.
string userName = null;
SPClaimProviderManager mgr = SPClaimProviderManager.Local;
if (mgr != null)
{
userName = mgr.DecodeClaim(SPContext.Current.Web.CurrentUser.LoginName).Value;
}
When I print the userName, I got the below output.
sp2013domain\spsetup

The DecodeClaim method is useful to retrieve the correct login name of the current user.

Comments