HttpWebRequest Sharepoint API Authentication FedAuth 401
-
17-12-2020 - |
Question
I already asked this question on StackOverflow Question on SO, but now I think I should have ask my question here in the first place.
I did some changes since I ask for help on SO, and my question is a bit different now.
This is the code I have
var adfsHelper = new ADFSHelper();
var cookie = adfsHelper.GetFedAuthCookie(domainName, userName, password);
ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback((object SearchOption, X509Certificate cert, X509Chain chain, SslPolicyErrors sslerror) => true));
var requestUri = "https://sharepoint/site/...._api/web/Lists/GetByTitle('ListName')/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.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
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();
// Get the stream associated with the response.
Stream receiveStream = endpointResponse.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
Console.WriteLine("Response stream received.");
Console.WriteLine(readStream.ReadToEnd());
}
catch (Exception e)
{
throw e;
}
My authentication workflow is the following, Request FedAuth token to the adfs server, then send it to the Sharepoint site insite my cookie.
I can browse the List with my IE, If I try use the cookie generated from my browser inside my code, I still have the 401 error.
Did I miss 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 how to send FedAuth Cookie :)
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange