I have to get current logged in user in provider hosted app event receiver.

I used the below code to get the current user name, but I got current user name as Sharepoint App instead of Current logged in user.

currentUser = clientContext.Web.CurrentUser;
clientContext.Load(currentUser, x => x.LoginName, y => y.Id);
clientContext.Load(currentUser, Z => Z.Title);

How to get the current logged in user?

  • is this app-only context ? – Gautam Sheth Jun 16 '17 at 9:33
  • yes this is app only context – Parthasarathy Jun 16 '17 at 9:48

If you are using app only context in your provider hosted app then you need to do a li'l extra work and use TokenHelper to get appOnlyAccessToken. On App's page load, just run the below script:

var contextTokenString = TokenHelper.GetContextTokenFromRequest(Page.Request);
Uri sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);
SharePointContextToken contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
string appOnlyAccessToken = TokenHelper.GetAppOnlyAccessToken(contextToken.TargetPrincipalName, sharepointUrl.Authority, contextToken.Realm).AccessToken;
using (var clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), appOnlyAccessToken))
                var currentUser = clientContext.Web.CurrentUser;                

                // TODO: display logged in user however you want

Well, I am your savior today. You can thank me later! :)

  • Thanks for your reply .but i am using remote event receiver.If i use this code in .svc file it shows error in Page.Request – Parthasarathy Jun 16 '17 at 10:44

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.