Reputation: 41
I need to develop a .NET Job that triggers an execution in the HPOO software, by calling API endpoint that requires a CSRF token.
Before I started coding, I tested the scenario in Postman:
Everything worked as expected when I did these tests in Postman.
When I try to implement the same scenario in code, the program blocks when calling the POST endpoint (passing the token).
Follow my code below:
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
var uriExecution = new Uri("https://hpoo-api.com.br/oo/rest/v2/executions");
var cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriExecution);
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Basic " + GetBasicAuthenticaton());
request.CookieContainer = cookies;
var response = request.GetResponse();
var csrf = response.Headers.Get("X-CSRF-TOKEN");
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(uriExecution);
request2.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request2.Headers.Add("Authorization", "Basic " + GetBasicAuthenticaton());
request2.Headers.Add("X-CSRF-TOKEN", csrf);
request2.CookieContainer = cookies;
var response2 = request2.GetResponse();
At the moment my code calls the method GetResponse()
of request2
, I get a exception saying I'm forbidden to access (403).
I tried with HttpClient
library too, but I got the same error, specifying that I'm forgetting the CSRF token.
Some things that I already tried which have not worked:
CookieContainer
, with all cookies in the first request, and pass to the request2.Please, someone could help me? Sorry for my bad english, brazilian here...
Upvotes: 2
Views: 6179
Reputation: 41
I found out the problem. Even colleting the cookies from first request and storing in a CookieContainer, the second request wasn't sending the cookies. After some search, I see its possible to send cookies in header, like this:
request.Headers.Add("Cookie", "cookie1=value1; cookie2=value2");
This way works like a charm, I only have to understand why using CookieContainer doesn't work...
Upvotes: 0