1

I have created a remote event receiver which is working fine. Now there is change in functionality such that, we have to bring some items from another site collection with in same web application, in remote event receiver.

I am creating context inside updated event of RER as below

using (ClientContext rootCtx = new ClientContext(rootSiteUrl))
{
}

But it is giving me 401 unauthorized error. My urls are like below

https://(server)/Teams    
https://(server)
1
  • You need to use an access token to authenticate with SharePoint, since the RER is Remote.
    – wjervis
    Mar 16, 2017 at 11:18

1 Answer 1

0

You need to use an access token to authenticate with SharePoint. You have to have the access token appended to the request headers for the ClientContext. If you already have the access token, you create the ClientContext as follows:

ClientContext clientContext = null;
try 
{
    clientContext = new ClientContext(targetUrl)
    {
        AuthenticationMode = ClientAuthenticationMode.Anonymous,
        FormDigestHandlingEnabled = false
    };
    clientContext.ExecutingWebRequest += (sender, eventArgs) => eventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = $"Bearer {accessToken}";
    // use clientContext
} 
finally
{
    clientContext?.Dispose();
}

If you are using the helper classes that are added by default, then you can use the method that the TokenHelper class exposes:

var context = SharePointContextProvider.Current.GetSharePointContext(HttpContext.Current);
using (var clientContext = TokenHelper.GetClientContextWithAccessToken(targetUrl, context.UserAccessTokenForSPHost))  // or use context.AppOnlyAccessTokenForSPHost if you want app permissions
{
    // use clientContext
}

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.