Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c# - How to pass Windows Authentication credential from client to Web API service

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Settings for web API

  1. Enable Windows Authentication

Settings for web application

  1. Enable Windows Authentication
  2. Add <identity impersonate="true" /> in <system.web> of web.config
  3. Add the following in the web.config:

     <system.webServer>
         <validation validateIntegratedModeConfiguration="false" />
     </system.webServer>
    
  4. 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...