0

Ejecuto una solicitud a una Rest Api y me devuelve codigo 200 OK, es decir que está bien pero no sé cómo obtener el token que devuelve

Mi codigo

public async Task PostParametrizadoAsync()
        {
            HttpClient client = new HttpClient();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token");
            var formData = new List<KeyValuePair<string, string>>();
            formData.Add(new KeyValuePair<string, string>("client_id", "api-stag"));
            formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
            formData.Add(new KeyValuePair<string, string>("username", "[email protected]"));
            formData.Add(new KeyValuePair<string, string>("password", "fsdfs34234"));
            formData.Add(new KeyValuePair<string, string>("scope", ""));
            request.Content = new FormUrlEncodedContent(formData);
            var response = await client.SendAsync(request);
            richTextBox1.Text = response.ToString();
        }

Me devuelve

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Transfer-Encoding: chunked
  Connection: keep-alive
  CF-RAY: 3c99d07f6d3d50c8-MIA
  Date: Thu, 07 Dec 2017 19:15:35 GMT
  Set-Cookie: __cfduid=dfca86d4feeaaaabb7395544081a3d8f61512674135; expires=Fri, 07-Dec-18 19:15:35 GMT; path=/; domain=.comprobanteselectronicos.go.cr; HttpOnly
  Server: cloudflare-nginx
  X-Powered-By: Undertow/1
  Content-Type: application/json
}
3
  • ¿Cómo esperas que te llegue ese token, por medio del response, como header?
    – Phi
    Commented el 7 dic. 2017 a las 21:12
  • El token lo devuelven en un json Commented el 22 ene. 2018 a las 21:06
  • Intenta leer la respuesta con fiddler o PostMan
    – sergiokml
    Commented el 28 oct. 2022 a las 5:41

2 respuestas 2

0

El token suele estar en

response.Content

Es decir en el body del response. Allí está el json que esperas.

0

Necesitarás crear un CookieContainer para recibir los cookies, algo similar a:

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
(...etc...)

Intenta con este código, sustituyendo los datos privados que espera tu servidor por los valores correctos:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
                    
public class Program
{
    public static void Main()
    {
        CookieContainer cookies = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler();
        handler.CookieContainer = cookies;
        
        HttpClient client = new HttpClient(handler);
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token");
        var formData = new List<KeyValuePair<string, string>>();
        formData.Add(new KeyValuePair<string, string>("client_id", "api-stag"));
        formData.Add(new KeyValuePair<string, string>("grant_type", "password"));
        formData.Add(new KeyValuePair<string, string>("username", "[email protected]"));
        formData.Add(new KeyValuePair<string, string>("password", "fsdfs34234"));
        formData.Add(new KeyValuePair<string, string>("scope", ""));
        request.Content = new FormUrlEncodedContent(formData);
        HttpResponseMessage response = client.GetAsync("https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token").Result;

        Uri uri = new Uri("http://google.com");
        IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri);
        foreach (Cookie cookie in responseCookies)
            Console.WriteLine(cookie.Name + ": " + cookie.Value);
        
        Console.WriteLine(response.ToString());
    }
}

Si pruebas este código de aquí abajo, tendrás un ejemplo práctico que funciona.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net;
                    
public class Program
{
    public static void Main()
    {
        CookieContainer cookies = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler();
        handler.CookieContainer = cookies;

        HttpClient client = new HttpClient(handler);
        HttpResponseMessage response = client.GetAsync("http://google.com").Result;

        Uri uri = new Uri("http://google.com");
        IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri);
        Console.WriteLine("Cookies");
        foreach (Cookie cookie in responseCookies)
            Console.WriteLine(cookie.Name + ": " + cookie.Value);
        
        Console.WriteLine("Respuesta:");
        Console.WriteLine(response.ToString());
    }
}

La respuesta que te enviará a la consola será similar a esta:

Cookies

    NID: 215=UKQ5UQ7uZVjuW9cI1iwCtTkYy7Alk69OW2iyUEAOUfaT_JgBzYZJUwr9NZLmnqXoZRlxTddxVQqvkT4omciSWjimkpARqXTi3grSWtQiRRXO9_u0tW3Fl3URd7Cd7W3lmhYqiwPdsxtj5fh5bDE6GRWcVMlKgfYYCZkl092eRA8
    Respuesta:
    StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
    {
      Date: Mon, 17 May 2021 14:46:05 GMT
      Cache-Control: max-age=0, private
      P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
      Server: gws
      X-XSS-Protection: 0
      X-Frame-Options: SAMEORIGIN
      Set-Cookie: 1P_JAR=2021-05-17-14; expires=Wed, 16-Jun-2021 14:46:05 GMT; path=/; domain=.google.com; Secure
      Set-Cookie: NID=215=UKQ5UQ7uZVjuW9cI1iwCtTkYy7Alk69OW2iyUEAOUfaT_JgBzYZJUwr9NZLmnqXoZRlxTddxVQqvkT4omciSWjimkpARqXTi3grSWtQiRRXO9_u0tW3Fl3URd7Cd7W3lmhYqiwPdsxtj5fh5bDE6GRWcVMlKgfYYCZkl092eRA8; expires=Tue, 16-Nov-2021 14:46:05 GMT; path=/; domain=.google.com; HttpOnly
      Accept-Ranges: none
      Vary: Accept-Encoding
      Transfer-Encoding: chunked
      Expires: -1
      Content-Type: text/html; charset=ISO-8859-1
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.