Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to authenticate with Rest-client based on HttpClient and .net4

Been elaborating a bit with HttpClient for building a rest client. But I can't figure out, nor find any examples on how to authenticate towards the server. Most likely I will use basic aut, but really any example would be appreciated.

In earlier versions (which has examples online) you did:

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

However the TransportSettings property no longer exists in version 0.3.0.

like image 531
Tomas Avatar asked Sep 12 '11 11:09

Tomas


People also ask

What is http preemptive authentication?

Preemptive basic authentication is the practice of sending http basic authentication credentials (username and password) before a server replies with a 401 response asking for them. This can save a request round trip when consuming REST apis which are known to require basic authentication.

How do I add basic authentication to HttpClient Java?

Let's add an authenticator to our client: HttpClient client = HttpClient. newBuilder() . authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("postman", "password".

What is HTTP client authentication?

HTTPS Client Authentication is a more secure method of authentication than either basic or form-based authentication. It uses HTTP over SSL (HTTPS), in which the server authenticates the client using the client's Public Key Certificate (PKC).


2 Answers

All these are out of date. The final way to do it is as follows:

var credentials = new NetworkCredential(userName, password); var handler = new HttpClientHandler { Credentials = credentials };  using (var http = new HttpClient(handler)) {     // ... } 
like image 85
Duncan Smart Avatar answered Sep 21 '22 19:09

Duncan Smart


The HttpClient library did not make it into .Net 4. However it is available here http://nuget.org/List/Packages/HttpClient. However, authentication is done differently in this version of HttpClient.

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

or

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); 

And be warned, this library is going to get updated next week and there are minor breaking changes!

like image 44
Darrel Miller Avatar answered Sep 21 '22 19:09

Darrel Miller