Search code examples
c#sharepointhttpwebrequest

HttpWebRequest Sharepoint API Authentication FedAuth 401


I need to get access to the Sharepoint _api/Web/Lists api. I have a FedAuth cookie that I will inject into my HttpWebRequest. This is my code

 ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback((object SearchOption, X509Certificate cert, X509Chain chain, SslPolicyErrors sslerror) => true));
        var requestUri = this._gedBaseUrl + @"_api/Web/Lists/GetByTitle('Title')/items?$filter=SomeKey eq 'SomeValue'";
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
        httpWebRequest.UserAgent = @"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
        httpWebRequest.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
        httpWebRequest.Method = WebRequestMethods.Http.Get;
        httpWebRequest.AllowAutoRedirect = false;
        httpWebRequest.Accept = @"text/html,application/xhtml+xml,*/*";
        httpWebRequest.CookieContainer = new CookieContainer();
        httpWebRequest.CookieContainer.Add(cookie);
        try
        {
            HttpWebResponse endpointResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        }
        catch (Exception e)
        {
            throw e;
        }

I have a WebException with the following header error:

((WebException)e).Response.Headers["X-MSDAVEXT_Error"]               "917656; Access denied. Before opening files in this location, you must first browse to the web site and select the option to login automatically."

So I decided to look at my browser's cookies, and I am sending the same things UserAgent and the FedAuth value.

So I am stuck with a http result 401.

This code works fine (http result 200) if I want to access to the Url without the @"_api/Web/Lists/GetByTitle('Title')/items?$filter=SomeKey eq 'SomeValue'";

I also try to add httpWebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); to my headers.

If I understood well, this header tell to the Sharepoint server to use the NTLM authentication, this not what I want, because my authentication method is based on FedAuth systeme.

I think I am missing something.


Solution

  • Finally,

    The _trust/ base url was the wrong one :/

    With the correct URL it is now working :)

    This question can now at least be used as a reference on how to send FedAuth Cookie :)