Create client C # (ASP.NET) to consume web service RESTFUL

3

I'm in trouble some time ago, for the first time I have to implement a client in C # (ASP.NET) that consumes a service exposed by a web application to create clients. I have reviewed different codes on the web like:

but the truth seems to me something very complex for what I need (although from what I have commented I have never worked with this subject).

I have the authentication credentials of the application (id and secret) to request the token, the URI and the structure to authenticate and request the token:

Structure

link

I hope you can help me please, I'm somewhat out of place and I do not know how to start this client, my doubts are:

  • with this information, how can I request the token?
  • when you get the token How to send it to get access to the functionalities of the web service?

I know the question is very colloquial, but I hope to be as explicit and simple as possible in my descriptions.

Thanks in advance

    
asked by Juan Hurtado 09.03.2016 в 22:24
source

1 answer

1

The structure of the url that you are putting http://id:secret@aplicacion/webservices/auth/token/ corresponds to the basic HTTP authentication protocol in which the user and password are sent as plain text.

That is the url works when you put it in the browser but with the class HttpClient is done differently.

The code would be the following:

var tokenUrl = "http://aplicacion/webservices/auth/token/";
HttpClient client = new HttpClient(handler);

var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
    "Basic", 
    Convert.ToBase64String(byteArray));

HttpResponseMessage response = await client.GetAsync(tokenUrl);
HttpContent content = response.Content;

// ... Comprobar el código de estado                                 
Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);

// ... Leer el token (en caso de que esté como texto plano)
string token = await content.ReadAsStringAsync();

It is assumed that in response.Content you would have the requested token, although you should check the documentation to see how it is returned and what the format is

Note : I have taken the code sample from here but I have not tried it myself if it works (although it should). In this ServerFault response explains the URL

By the way, when you put it into production it would be convenient to use a secure SSL connection because the user and password are in plain text. The code should work simply by changing http by https

    
answered by 10.03.2016 / 17:56
source