I have created a console application by using this tutorial:


With some differences of course, in my console app, I want to make a rest call to the search api.

Read this: Giving the App Principal Permissions Instead of using tenant manage as in the example I used this:

    <AppPermissionRequest Scope="https://sharepoint/search" Right="QueryAsUserIgnoreAppPrincipal" />

Then I went to “_layouts/AppInv.aspx”. And registered the app using the client id and the xml above.

Then I clicked on Trust it.

My app.config is like this:

<xml version="1.0" encoding="utf-8" ?>
    <section name="Sites"
    <add key="ClientId" value="xx-1c6c-45e7-8a2a-7364a705c836"/>
    <add key="ClientSecret" value="+xx="/>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    <add key="site1" value="https://xx.sharepoint.com/sites/developersitecollection"/>

Then my console app fails with Unauthorized Exception on the getresponde

 static void Main(string[] args)
            var config = (NameValueCollection)ConfigurationManager.GetSection("Sites");

            foreach (var key in config.Keys)
                Uri siteUri = new Uri(config.GetValues(key as string)[0]);

                using (ClientContext clientContext = new ClientContext(siteUri))
                    string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
                    string accessToken =
                        siteUri.Authority, realm).AccessToken;

                    HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(siteUri +"/_api/search/query?querytext=%27*.pptx%27");
                    endpointRequest.Method = "GET";
                    endpointRequest.Accept = "application/json;odata=verbose";
                    endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
                    HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
                    StreamReader reader = new StreamReader(endpointResponse.GetResponseStream());
                    var searchXml = new XmlDocument();


I have added this into the xml AllowAppOnlyPolicy="true"

and now the code shows me a different error, already asked a question about that error here:


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.