4

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);
clientContext.ExecuteQuery();

How to get the current logged in user?

2
  • is this app-only context ? Jun 16, 2017 at 9:33
  • yes this is app only context Jun 16, 2017 at 9:48

1 Answer 1

3

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;                
                clientContext.Load(currentUser);                              
                clientContext.ExecuteQuery();

                // TODO: display logged in user however you want
            }

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

1
  • 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 Jun 16, 2017 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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