How can I get Current Logged in user of SharePoint Site in Provider Hosted App's code behind since the app is Provider Hosted, using S2S and with App-Only policy

I tried this:

Web web = clientContext.Web;

currentUser = clientContext.Web.CurrentUser.LoginName;

I am getting all the time a user i:0i.t|<some key>|app@sharepoint. It looks like an user exclusive for the App as the definition in policy types says (msdn).

I would like to have your help on this, since I need to work in app context with the user that is logged in Sharepoint Portal, and where is rendered the app into a page. I suppose I have to change the policy the app for a App+user policy, and if yes, how can I force this policy?

  • Which is the scope of the app? Do you have the read permission? – Nk SP Nov 12 '14 at 13:16
  • I have 2 scopes defined. Site Collection - Full Control, and Web - Full Control. – Hugo Barona Nov 12 '14 at 17:24

You'll get SharePoint app identity if your app is provider hosted and app only. If this is Asp.Net MVC app, you can always get logged in user from HttpContext as below. HttpContext.Current.User.Identity.Name
Pass this as parameter

User user = clientContext.Web.EnsureUser(HttpContext.Current.User.Identity.Name);
  • HttpContext.Current.User.Identity won't be set if you're running an Azure Web App, because it would require Windows Authentication enabled in IIS which is not possible for Azure. – Thiago Silva Oct 9 '15 at 22:12

In your SharePoint app,locate Appmanifest.xml and uncheck app only call from permission tab, Use following code to read current logged in user

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

using (var clientContext = spContext.CreateUserClientContextForSPHost())

Try this code :-

Web web = clientContext.Web;
clientContext.Load(web, w => w.CurrentUser);
currentUser = clientContext.Web.CurrentUser.Name;
  • I tried the code but gives me the same user that i mentioned before. – Hugo Barona Nov 12 '14 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.