Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPContext.Current.Web.CurrentUser returns misleading value

I'm trying to find out current user name for my sharepoint application. There are more that one way how to do this. However the sharepoint way returns misleading value.

System.Security.Principal.WindowsIdentity.GetCurrent().Name // returns MY_COMPUTER\\my_user

HttpContext.Current.User.Identity.Name // returns MY_COMPUTER\\my_user

HttpContext.Current.Request.ServerVariables["AUTH_USER"] // returns MY_COMPUTER\\my_user

Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.LoginName // returns SHAREPOINT\\system

What is the cause of this behavior? Will I encounter problems if I'll use non-sharepoint way?

like image 352
Jakub Šturc Avatar asked Jan 05 '09 16:01

Jakub Šturc


4 Answers

Are you browsing as the admin account that you used to install the system? SharePoint will "helpfully" rename that SHAREPOINT\System. Use a different account and all of the methods will return the same value.

like image 68
jwmiller5 Avatar answered Oct 26 '22 23:10

jwmiller5


This is expected if the user is the application pool account running the current web application.
BTW, it's supposed to be the same name as displayed in the welcome control (upper left control)

like image 31
Nico Avatar answered Oct 27 '22 00:10

Nico


The problem is because you are probably getting the current user from an elevated SPWeb inside a RunWithElevatedPrivileges code. You can use the snippet below to get the real user

SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID))
   {
       using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID))
       {
            string currUser = site.CurrentUser; //not the ElevatedSite.CurrentUser
       }
   }
});

This will show the real user name instead of the SHAREPOINT\System user.

like image 45
user432195 Avatar answered Oct 27 '22 01:10

user432195


I think you might have include this code under SPSecurity.RunWithElevatedPriviliges. Check it out once. I am not sure though

like image 23
Ajju Avatar answered Oct 26 '22 23:10

Ajju