3

I have created one provider hosted app for remote event receiver. In that, I want to make a REST call with c#. below is my code but I 'm getting 401 unauthorized,

            Uri targetWeb = new Uri(clientContext.Web.Url);
            string targetRealm = TokenHelper.GetRealmFromTargetUrl(targetWeb);
            var responseToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm);
            HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(strApiUrl);
            endpointRequest.Headers.Add("Authorization", String.Format("{0} {1}", responseToken.TokenType, responseToken.AccessToken));
            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json;odata=verbose";
            endpointRequest.Credentials = clientContext.Credentials;
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            WebResponse webResponse = endpointRequest.GetResponse();
            webStream = webResponse.GetResponseStream();

Can anyone know how to achieve this?

2

My problem solved by setting AllowAppOnlyPolicy to true in appmanifest.xml file & passing realm & AppOnlyAccessToken as Authorization header in Http Request as below,

Uri targetWeb = new Uri(clientContext.Web.Url);
string targetRealm = TokenHelper.GetRealmFromTargetUrl(targetWeb);
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, targetWeb.Authority, targetRealm).AccessToken;                
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(strApiUrl);
endpointRequest.Headers.Add("Authorization", "bearer "+ accessToken);

Below is reference link from MSDN

https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/elevated-privileges-in-sharepoint-add-ins

1

Please try this link by Waldek Mastykarz. I guess it is because cross domain call please try this one also Hope this will solve your problem. Please feel free to reply it it works or not

All the best!

  • 2
    do not post link only answers. the links might go dead in future and this answer will become worthless – Abdul Hameed Apr 4 '18 at 6:59

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.