Первый: Получить строку токена CSRF из GET_API_URL. Это отлично работает.
Секунда: Сделать POST для POST_API_URL с полученной строкой CSRF.
Проблема в том, что независимо от того, что я пытался, он продолжал получать 403 Запрещенную ошибку во втором ответе. Попытались сохранить файлы cookie первого ответа (3 файла cookie - 2 безопасных) в контейнере файлов cookie, а затем передать его второму запросу. Все еще не повезло ...
Пробовал такое же соединение на POSTman, все работало нормально. Только не в C #.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://mysap_get-api.s4hana.ondemand.com/blablabla");
req.Proxy = null;
req.Method = "GET";
req.Headers["X-CSRF-Token"] = "fetch";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(auth_key));
req.CookieContainer = cookieContainer;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
string csrf = response.GetResponseHeader("x-csrf-token");
if (!string.IsNullOrEmpty(csrf))
{
try
{
HttpWebRequest post_req = (HttpWebRequest)WebRequest.Create("https://mysap_post-api.s4hana.ondemand.com/blablabla");
post_req.Proxy = null;
post_req.Method = "POST";
post_req.ContentType = "application/json";
post_req.Headers["APIKey"] = api_key;
post_req.Headers["X-CSRF-Token"] = csrf;
post_req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(auth_key));
post_req.Accept = "text/xml";
post_req.CookieContainer = cookieContainer;
//tried this as well - no luck
//foreach (Cookie _cookie in response.cookies)
//{
// cookieContainer.Add(new Cookie
// {
// Name = _cookie.Name,
// Value = _cookie.Value,
// Secure = _cookie.Secure,
// Domain = "mysap_post-api.s4hana.ondemand.com"
// });
//}
//attach json body
JavaScriptSerializer js = new JavaScriptSerializer();
string _hourJson = js.Serialize(_hour);
var data = Encoding.ASCII.GetBytes(_hourJson);
using (var post_reqStream = post_req.GetRequestStream())
{
post_reqStream.Write(data, 0, data.Length);
}
// Post second request and retrieve result
string result;
***THIS KEEP GIVING 403!!!***
using (WebResponse post_response = post_req.GetResponse())
{
using (StreamReader rd = new StreamReader(post_response.GetResponseStream()))
{
result = rd.ReadToEnd();
}
}
}
catch (Exception ex)
{
}
}
else
{
Debug.WriteLine("Invalid CSRF token, job terminated");
}