2

I have the following function declared in a web API controller. IIS Server is configured for the Web API to use Forms Authentication (can't enable Basic authentication due to customer restrictions):

[HttpGet]
[Authorize]
[Route("")]
public ContactDTO GetPharmacy()
{
    return ToContactDTO(customerContext.CurrentContact);
}

Using this service as a logged user from a webbrowser using Jquery Ajax ($.ajax(...)) works fine and perfectly. However I want to do the same thing using the HttpClient class from .Net. I tried the following, yet without any success, always getting a 401 Unathorized response.

using (var client = new HttpClient())
{
     client.BaseAddress = new Uri("http://localhost:17200");

     AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Forms", Convert.ToBase64String(new ASCIIEncoding().GetBytes(String.Format("{0}:{1}", "admin", "123456"))));
     client.DefaultRequestHeaders.Authorization = authHeader;
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

     HttpResponseMessage response = client.GetAsync("/api/pharmacies").Result;
}

How should I use the HttpClient to work with forms Authentication?

Thank you.

David Jiménez Martínez
  • 3,053
  • 5
  • 23
  • 43

1 Answers1

1

For forms authentication you need to provide auth cookie. To get that cookie you can use approach described there. And then you need to build your api request with that cookie. If something is not working you can always compare you requests to original ones that you made from your browser.

Community
  • 1
  • 1
Vladimirs
  • 8,232
  • 4
  • 43
  • 79
  • 2
    Thank you for your answer. As I've seen in this link (http://www.asp.net/web-api/overview/security/forms-authentication) that forms authentication is not suitable outside a web-browser context, I'll ask another question regarding Basic and Forms authentication. – David Jiménez Martínez Oct 09 '14 at 15:48