2

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;

 GetSearchResponse(httpWebRequest)

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



         stack trace : "{\"error\":{\"code\":\"-2147024891, 
            System.UnauthorizedAccessException\",\"message\":{\"lang\":\"en-US\",\"value\":\"Access   
         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 ''.]
0

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;
0

using client side we can get FormDigest value

$.ajax({
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, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.