Note: Please do not make my question as duplicate, still i haven't get any proper answer for my question.

I am getting 401 unauthorized error when calling a sharepoint search rest api (/_api/search/query?querytext) from a .net application using claims based authentication.

My request and error as below

httpWebRequest.Headers["X-RequestDigest"] = GetDigestForPostRequest;
 httpWebRequest.Headers["Authorization"] = "Bearer " + generateClaimsIdentityToken;


    private void GetSearchResponse(HttpWebRequest httpWebRequest)
                        using (var httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
                            using (var stream = httpWebResponse.GetResponseStream())
                    catch (WebException ex)
                    {//catch and log the error

         stack trace : "{\"error\":{\"code\":\"-2147024891, 
         denied. You do not have permission to perform this action or access 
        this resource.\"}}}"

    [MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was ''.]

2 Answers 2


You need to call the spcontextinfo through rest and get the FormDigest first.

Call http://server/web/doclib/forms/_api/contextinfo using POST

Then get the formDigestValue from the response.

Then use that value in your headers:

request.Headers["X-RequestDigest"] = formDigestValue;

using client side we can get FormDigest value

url: "/sites/prashant/_api/contextinfo",
method: "POST",
data: JSON.stringify,
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, status, xhr)  
       var formdigest= data.d.GetContextWebInformation.FormDigestValue;
            console.log(data, status, xhr);  
        error: function(xhr, status, error)  
            console.log(xhr, status, error);



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.