Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.3K
Vistas
Cómo usar HttpClient para publicar con autenticación

Estoy tratando de hacer el siguiente curl (que funciona para mí) en C# usando HttpClient.

 curl -X POST http://www.somehosturl.com \ -u <client-id>:<client-secret> \ -d 'grant_type=password' \ -d 'username=<email>' \ -d 'password=<password>' \ -d 'scope=all

El código C#:

 HttpClientHandler handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential ("my_client_id", "my_client_secret") }; try { using(var httpClient = new HttpClient(handler)) { var activationUrl = "www.somehosturl.com"; var postData = "grant_type=password&username=myemail@myemail.com&password=mypass&scope=all"; var content = new StringContent(postData, Encoding.UTF8, "application/x-www-form-urlencoded"); var response = await httpClient.PostAsync(activationUrl, content); if(!response.IsSuccessStatusCode) return null; var result = await response.Content.ReadAsStringAsync(); return result; } } catch(Exception) { return null; }

Cuando se ejecuta, simplemente falla, ni siquiera detecta la excepción

Normalmente puedo GET y POST perfectamente bien, pero lo que me desconcierta es cómo configurar las cosas de autenticación (id de cliente y secreto de cliente)

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Primero debe configurar el encabezado de Authorization con su <clientid> y <clientsecret> .

En lugar de usar StringContent , debe usar FormUrlEncodedContent como se muestra a continuación:

 var client = new HttpClient(); client.BaseAddress = new Uri("http://myserver"); var request = new HttpRequestMessage(HttpMethod.Post, "/path"); var byteArray = new UTF8Encoding().GetBytes("<clientid>:<clientsecret>"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray)); var formData = new List<KeyValuePair<string, string>>(); formData.Add(new KeyValuePair<string, string>("grant_type", "password")); formData.Add(new KeyValuePair<string, string>("username", "<email>")); formData.Add(new KeyValuePair<string, string>("password", "<password>")); formData.Add(new KeyValuePair<string, string>("scope", "all")); request.Content = new FormUrlEncodedContent(formData); var response = await client.SendAsync(request);
over 4 years ago · Santiago Trujillo Denunciar

0

Intente colocar sus credenciales directamente en la propiedad de encabezados de HttpClient.

 using (var client = new HttpClient()) { var byteArray = Encoding.ASCII.GetBytes("my_client_id:my_client_secret"); var header = new AuthenticationHeaderValue("Basic",Convert.ToBase64String(byteArray)); client.DefaultRequestHeaders.Authorization = header; return await client.GetStringAsync(uri); }
over 4 years ago · Santiago Trujillo Denunciar

0

Ver BasicAuthenticationHeaderValue

 httpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue("login", "password");

O use extensiones de IdentityModel:

 <PackageReference Include="IdentityModel" Version="4.0.0" /> var client = new HttpClient(); client.SetBasicAuthentication(login, password); client.SetBearerToken(token);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda