0

I'm testing the API https://imunizacao-es.saude.gov.br/_search with basic auth using the following credentials:

login: immunizacao_public and password: qlto5t&7r_@+#Tlstigi -

The filter below works well in Postman, but when I test using the project, I get the Forbidden error. What can it be?

private readonly string _searchUrl = "https://imunizacao-es.saude.gov.br/_search";
private readonly string _username = "imunizacao_public";
private readonly string _password = "qlto5t&7r_@+#Tlstigi";

  private async Task<int> ObtainTotalNumberVaccinated(DateTime applicationDate)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                //Set authentication credentials
                string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_username}:{_password}"));
       

                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                // Build the body of the request to get the total number of vaccinated
                string requestBody = @"{
            ""query"": {
                ""bool"": {
                    ""must"": [
                        {
                            ""match"": {
                                ""vacina_fabricante_nome"": ""PFIZER""
                            }
                        },
                        {
                            ""match"": {
                                ""estabelecimento_uf"": ""RJ""
                            }
                        },
                        {
                            ""match"": {
                                ""vacina_dataAplicacao"": """ + applicationDate.ToString("yyyy-MM-dd") + @"""
                            }
                        }
                    ]
                }
            }
        }";
                HttpContent content = new StringContent(requestBody, Encoding.UTF8, "application/json");

                //Send POST request to get the total amount vaccinated
                HttpResponseMessage response = await httpClient.PostAsync(_searchUrl, content);
                string responseContent = await response.Content.ReadAsStringAsync();

                // Parse the response content to get the total vaccinated count
                dynamic jsonResponse = JsonConvert.DeserializeObject(responseContent);
                int TotalNumberVaccinated = jsonResponse.hits.total.value;
                return totalNumberVaccinated;
            }
        }

I need to receive the total number of vaccinated, which comes from the API.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

Try this solution.

In short, it seems you need to set the Authorization header not on httpClient directly, but use HttpRequestMessage and post that.

Andrea
  • 24
  • 3