Cómo autenticarse con Rest-client basado en HttpClient y. net4


Estado elaborando un bit con HttpClient para construir un cliente rest. Pero no puedo averiguar, ni encontrar ningún ejemplo sobre cómo autenticarse hacia el servidor. Lo más probable es que use aut básico, pero realmente cualquier ejemplo sería apreciado.

En versiones anteriores (que tiene ejemplos en línea) usted hizo:

HttpClient client = new HttpClient("http://localhost:8080/ProductService/");
client.TransportSettings.Credentials =
    new System.Net.NetworkCredential("admin", "admin");

Sin embargo, la propiedad TransportSettings ya no existe en la versión 0.3.0.

Author: Tomas, 2011-09-12

6 answers

Todos estos están desactualizados. La forma final de hacerlo es la siguiente:

var credentials = new NetworkCredential(userName, password);
var handler = new HttpClientHandler { Credentials = credentials };

using (var http = new HttpClient(handler))
{
    // ...
}
 75
Author: Duncan Smart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-22 23:31:13

La biblioteca HttpClient no llegó a.Net 4. Sin embargo, está disponible aquí http://nuget.org/List/Packages/HttpClient . Sin embargo, la autenticación se hace de manera diferente en esta versión de HttpClient.

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization 
                   = new AuthenticationHeaderValue("basic","...");

O

var webRequestHandler = new WebRequestHandler();
CredentialCache creds = new CredentialCache();
creds.Add(new Uri(serverAddress), "basic",
                        new NetworkCredential("user", "password"));
webRequestHandler.Credentials = creds;
var httpClient = new HttpClient(webRequestHandler);

Y tenga cuidado, esta biblioteca se va a actualizar la próxima semana y hay pequeños cambios de última hora!

 17
Author: Darrel Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-12 12:49:48

Probé la sugerencia de Duncan, pero no funcionó en mi caso. Sospecho que fue porque el servidor con el que me estaba integrando, no envió un desafío o pidió autenticación. Simplemente rechazó mis solicitudes, porque no proporcioné un encabezado Authorization .

Así que hice lo siguiente:

using (var client = new HttpClient())
{
    var encoding = new ASCIIEncoding();
    var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", "username", "password"))));
    client.DefaultRequestHeaders.Authorization = authHeader;
    // Now, the Authorization header will be sent along with every request, containing the username and password.
}

Observe que el ejemplo aquí solo funciona con Autenticación básica.

 8
Author: René,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-15 17:09:52

Por si sirve de algo, nada de usar HttpClientHandler funcionó, al menos no para intentar hacer una llamada autenticada a la API de CouchDB que requiera credenciales de administrador del servidor.

Esto funcionó para mí:

using( var client = new HttpClient() )
{
    var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
    ....
}

Como se describe en la respuesta aquí:

¿Cómo usar credenciales en HttpClient en c#?

 1
Author: ChrisCW,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:48

Creo que esto es un poco viejo, pero para cualquiera que busque una respuesta actualizada, utilicé este código cuando construí mi servidor de prueba:

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://myServer/api/Person");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var byteArray = Encoding.ASCII.GetBytes($"{UserName}:{ApiPassword}");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

O esto también funciona:

            using (var http = new HttpClient())
            {
                // byteArray is username:password for the server
                var byteArray = Encoding.ASCII.GetBytes("myUserName:myPassword");
                http.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                string uri = "http://myServer/api/people" ;
                var response = await http.GetStringAsync(uri);
                List<Person> agencies = JsonConvert.DeserializeObject<List<Person>>(response);
                foreach (Person person in people)
                {
                    listBox1.Items.Add(person.Name);
                }
            }
 1
Author: GaryP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-08 11:02:53

Acabo de descargar 0.3.0 de hecho se ha eliminado. Ahora está en HttpClientChannel

HttpClient client = new HttpClient(...);
var channel = new HttpClientChannel();
channel.Credentials = new NetworkCredential(...);
client.Channel = channel;

Si no se especifica explícitamente, utiliza una instancia predeterminada de HttpClientChannel.

ACTUALIZAR: esto ahora no es válido para. Net 4.5; consulte la respuesta correcta a continuación: https://stackoverflow.com/a/15034995/58391

 0
Author: TheCodeKing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:49