Inside my corporate environment, I have IIS7.5 hosting both a Web API service and a separate website which makes calls into that service via the RestSharp library. Both are currently configured with Windows Authentication.
If I navigate to either one with a browser, I'm prompted to enter my windows credential, and everything works great... I get web pages that I want and the REST service spits out my data. The part I'm struggling to figure out is how to use a single credential to authentication both. I can't figure out how to either pass the Website's credential to the service (I tried impersonating but it didn't work), or to manually prompt the user for username/password and then authenticate them with "Windows".
Help a noob out?
Windows authentication enables users to log in with their Windows credentials, using Kerberos or NTLM. The client sends credentials in the Authorization header. Windows authentication is best suited for an intranet environment.
Application credential requirements The client must create a POST call and pass the user name, password, and authString in the Request headers using the /x-www-form-urlencoded content type. The AR System server then performs the normal authentication mechanisms to validate the credentials.
In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.
Settings for web API
Windows Authentication
Settings for web application
Windows Authentication
<identity impersonate="true" />
in <system.web>
of web.configAdd the following in the web.config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Enable Windows Authentication
and ASP.NET Impersonation
within IIS
You can use the following code to POST data to web API (and GET as well obviously)
using (var client = new WebClient { UseDefaultCredentials = true })
{
client.Headers.Add(HttpRequestHeader.ContentType, "application/xml; charset=utf-8");
byte[] responseArray = client.UploadData("URL of web API", "POST", Encoding.UTF8.GetBytes(XMLText));
string response = Encoding.ASCII.GetString(responseArray);
}
NOTE: If you're still getting 401 errors you may need to use an IP address instead of a regular domain name for your URL (e.g.: 155.100.100.10 instead of mycompany.com)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With