Monday, July 29, 2013

Non-interactive Authentication to ASP.NET Web API using HTTPClient

HttpClient is a new HTTP library in .NET for accessing HTTP request. It is powerful library to utilize and get benefit of HTTP protocol. You can download it using NuGet.

In order to call authenticate service, the HTTPClient has to be authenticated with non-interactive way. On the other hand, the service has to have a login option for non-interactive client.


The following code snippet shows how we can allow non-interactive user to login:

public HttpResponseMessage PostJsonLogin(LoginModel model)
{
   if (ModelState.IsValid)
      {
       if (true)//Validate User
          {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            return Request.CreateResponse(HttpStatusCode.OK, true);
           }
       }
    return Request.CreateResponse(HttpStatusCode. Unauthorized, false);
}


Here, if the user is valid, it will pass the authentication cookie and set the HTTP status code OK.

To call any authenticate service, the HTTPClient itself has to be authenticated by calling the PosrJsonLogin action. The following pseudo code shows how we can call an authenticate action:

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

var client = new HttpClient(handler);
client.BaseAddress = new Uri("http://localhost:9712/baseurl ");
          

var model = new { UserName = "Gizmo", Password = "123", RememberMe = true };
HttpResponseMessage response = client.PostAsJsonAsync("api/Account/JsonLogin", model).Result;

if(response.IsSuccessStatusCode)
{
   var result = client.GetStringAsync("api/ContentManagement").Result;
}

In the above code snippet, it’s calling JsonLogin which will reply authentication cookie. If the HTTP status code is 200/OK, it can call any authenticate action.

You can download the source code from here.

Hope this helps!  

No comments: