How to pass Windows Authentication credential from client to Web API service

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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?

回答1:

If you use impersonation on your web site and the API is running on the same server it should work.

http://msdn.microsoft.com/en-us/library/aa292118(v=vs.71).aspx

However, if you would move the API to a different server from the site this will stop working. A two-server setup requires Kerberos delegation.



回答2:

After spending my two days on this I have found the solution.

Settings for web API Enable Windows Authentication on you web API.

Settings for web Application Enable Windows Authentication on you web Application. Add system.web of web.config. Add

in web.config

Enable Windows authentication and ASP.NET Impersonation from IIS.

User following code to post data on Web API (and similarly for Getting)

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: Most Important thing is always call your web api via IP if you use URL you may always get 401 Unauthorized Error.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!