Authentication in Restful Service

Asked

Viewed 4,228 times

4

In the example below, I need to pass a login pair/password, because the REST service requires authentication (Basic Authentication). So how should I pass this information in the section below? (Additional information: authentication must be done encoded in the upload header)

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://dominio:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}
  • 1

    It depends on the implementation of the REST service you are trying to use. Some ask for the API key as an optional parameter, others ask for a password/login pair in the headers. View the API documentation and change the question.

  • Dear Rodrigo, I did as oriented. It is not optional, it should be covered in Header. All the API documentation is geared towards JAVA, I’m having a hard time with this. Thank you.

2 answers

2


In the header of the request http you can pass an argument called Authorization. According to the http documentation, this argument by default expects you to report, a schema authentication and a token. You can customize this information if the API needs it, but by default the schema used by the browser are: Basic and the token contains the following format: login:senhar in base64.

You can try it:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://dominio:9000/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    client.Headers.Authorization = new AuthenticationHeaderValue("Basic", 
                    Convert.ToBase64String(
                                System.Text.ASCIIEncoding.ASCII.GetBytes(
                                    string.Format("{0}:{1}", "seuUsuario", "suaSenha"))));

    // New code:
    HttpResponseMessage response = await client.GetAsync("api/products/1");
    if (response.IsSuccessStatusCode)
    {
        Product product = await response.Content.ReadAsAsync>Product>();
        Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
    }
}
  • 1

    Perfect Felipe! It worked perfectly, thank you.

  • Cool Santana, happy to help. If possible mark as solution and send a voteup to collaborate with the website and for other users to find the solution to a similar problem. :)

  • Done! Thanks again.

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.