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=allEl 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)
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);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); }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);