Authentication in RESTFul service

3

In the example below, I need to pass a login / password pair because the REST service requires Basic Authentication. So how do I pass this information in the following section? (Additional information: authentication must be made encoded in the send 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);
    }
}
    
asked by anonymous 08.09.2014 / 21:08

2 answers

1

At the request header http you can pass an argument named Authorization . According to http documentation , this argument expects you to report a schema of authentication and token . You can customize this information if the API requires, but by default the schema used by the browser is: Basic and the token, contains the following format: login:senhar at base64 .

You can try this:

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);
    }
}
    
09.09.2014 / 23:03
0

After researching the subject, I discovered a path that not only elucidates but complements the general knowledge about this subject. So for anyone who wants to learn more about: Web Security API , go to this URL [: link

Hugs.

    
09.09.2014 / 22:55