Skip to Content

403 Forbidden when Posting to API from .NET HttpWebRequest

First method: Get the CSRF token string from an GET_API_URL. This works fine.

Second method: Make a POST to POST_API_URL with the obtained CSRF string.

Problem is, no matter what I tried, it kept getting 403 Forbidden error. Have tried storing first response's cookies (3 cookies - 2 are secure) into a Cookie Container, then pass it to second request. Still no luck...

Tried the same connection on POSTman, all worked fine. Just not in 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");
        }
Add comment
10|10000 characters needed characters exceeded

  • Get RSS Feed

0 Answers