简体   繁体   中英

How to run Sharepoint Rest API from server side with elevated privileges?

The Sharepoint Rest API uses a simple URL of the type http://mysite/_api/search/query?querytext='search_key' to return search results as an XML. When I run this directly in a browser, I see a valid XML response:

其余API输出

(1) Am I right in assuming the above response is generated using the current user's authorization?

(2) Can this URL be invoked from server side? I tried it in a web method (WCF web service), but received a 401 - Unauthorized :

public string GetSearchResults(string searchKey)
{
    string webURL = SPContext.Current.Web.Url;
    string searchURL = webURL + "/_api/search/query?querytext='" + searchKey + "'";
    WebClient client = new WebClient();
    string xmlResponse = client.DownloadString(searchURL); // throws 401

    // parse xmlResponse and return appropriately
}

(3) What I really need is to be able to get the search results irrespective of the current user's access rights (the requirement is that users will see all search results, with an option to "request access" when needed).

I tried this in the above web method, but it still throws the same 401 :

public string GetSearchResults(string searchKey)
{
    string webURL = SPContext.Current.Web.Url;
    string searchURL = webURL + "/_api/search/query?querytext='" + searchKey + "'";
    string xmlResponse;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        WebClient client = new WebClient();
        xmlResponse = client.DownloadString(searchURL); // still 401
    });

    // parse xmlResponse and return appropriately
}


What is the right way to invoke the Rest URL from server side? Specifically, from a web method? And how can it be run as super user?

In order to perform REST request, authenticate the request via WebClient.Credentials Property

On Premise (your scenario)

WebClient client = new WebClient();
client.Credentials = new NetworkCredential(userName,password,domain);

SharePoint Online

WebClient client = new WebClient();
client.Credentials = new SharePointOnlineCredentials(username,securedPassword);
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");

Search results are always security trimmed by SharePoint so to make this work, you'd need to run your query after specifying new credentials as mentioned by Vadim. This is almost certainly not a good idea. If you're running code server side already, don't use the REST interface, just query directly using the search API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM