Windows Authentication in ASP .Net for WebApi - c#

I have written a simple ASP.Net WebAPI that download a file from an on-prem tfs server using a rest call. The issue is when I connect to this site from my user account(corp domain), and set the credentials in webRequest to CredentialsCache.DefaultCredentials, it works fine since I am a vlid user on the tfs project.
Now someone else in my team wishes to use the same webAPI and when they hit the same url, I could see that its my credentials being used again to download the file.
I suspect this is because of using CredentialsCache.DefaultCredentials in my controller code, but I am not able to find a way using which I should be able to use the client's identity to be used for the download request.
My question is , is there a way to extract the windows identity or network credentials of the remote user(on the same domain) which I can use for Authentication. I am sorry if this is a DUP but I could not find a targetted answer to my question yet. Sample code is pasted below.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var webResponse = request.GetResponse();
var webStream = webResponse.GetResponseStream();
if (webStream != null)
{
var objReader = new StreamReader(webStream);
return objReader.ReadToEnd()
}
}

I dont know if I understand you correctly but I think impersonation is what you're looking for:
http://msdn.microsoft.com/en-us/library/xh507fc5.ASPX

Related

WebRequest Works Locally, but Not When Published

I have run into a snag while building a web client that makes use of a RESTful web service using Integrated Windows Authentication.
When I run the client locally (as myself), it works fine, and I see my user id in the IIS logs. But, when I run it remotely, no credentials are passed (i.e. I do not see my user id in the IIS logs), and I get an error that
"The remote server returned an error: (401) Unauthorized."
Both the local and published client call the same service. Also note that the IIS logs show two entries (one without a username and one with a username) when I run it locally. When I run in from the published location, there are still two entries, but neither shows the username.
Below is the code I am using to make the call:
var request = (HttpWebRequest) WebRequest.Create(ConfigurationManager.AppSettings["positionServicePath"] + "?positionNumberSearch=" + searchString);
request.Method = "GET";
request.ContentType = "application/json";
request.UseDefaultCredentials = true;
request.PreAuthenticate = false;
CredentialCache cc = new CredentialCache();
cc.Add(
new Uri(ConfigurationManager.AppSettings["positionServicePath"]),
"Negotiate",
CredentialCache.DefaultNetworkCredentials);
request.Credentials = cc;
// Get the Response
using (var response = request.GetResponse()){
var reader = new StreamReader(response.GetResponseStream());
// Convert the response to objects from Json
var resultList = JsonConvert.DeserializeObject<IEnumerable<PositionModel>>(reader.ReadToEnd());
// Return an empty list, if no data was retrieved
return resultList != null ? resultList.ToList() : new List<PositionModel>();
}
Any help would be greatly appreciated.
I think you have to create IIS user permitted to your project.
Follow this Anonymous Access
Second Option:
Try to enabled anonymous access in Authentication Methods in Microsoft Internet Information Services (IIS).
Step:
1. Open your IIS.
2. In IIS Group:
3. open or select Authentication:
4. Select Anonymous Authentication:
5. On the Left Side select Enabled.
Good Luck!
I found the answer to this issue was the same for the answer to the following Stack Overflow post: Unable to authenticate to ASP.NET Web Api service with HttpClient.
Thank you to those who took the time to look this over!

asp.net defaultCredentials issue

I have an intranet site which calls a POST method from another server, also on the intranet.
If I set the Authentication mode to Basic Authentication in IIS I can use the following:
HttpWebRequest oReq = (HttpWebRequest)WebRequest.Create(sURL);
oReq.ContentType = "application/x-www-form-urlencoded";
oReq.Method = "POST";
oReq.Timeout = 60000;
...
oReq.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
...
try
{
HttpWebResponse oResp = (HttpWebResponse)oReq.GetResponse();
...
}
All of the above works as intended.
However I need to change the security to Windows Authentication in IIS, and once I do I keep getting error 401 unauthorized on this line:
try
{
HttpWebResponse oResp = (HttpWebResponse)oReq.GetResponse();
...
}
That can be fixed by changing the credentials like so:
NetworkCredential creds = new NetworkCredential("username","password","domain");
oReq.Credentials = creds;
But that's not the right way anyway. How can I get the default credentials to work for Windows Authentication also?
If you've got one web site calling out to another, you've got a 2nd hop. This is a kerberos 2nd hop problem.
The intranet site needs permission to call the 2nd site on behalf on the end user.
I'd suggest you use a tool call DelegConfig. I can't recommend it highly enough. Its a simple asp.net application that will tell you what is wrong with your kerberos setup and can tell you how to fix it (or do it itself if you want)
I've found I had to get the client to server authentication working first for it it work, but once thats there it makes working out what wrong with the next hop to UNC/http/sql etc very easy.

open ssrs report in Excel format via 'normal' url with webrequest returns 401

i want to download a ssrs report in Excel format in code.
So i first checked the url: it is correct
then i created a webrequest, with a NetworkCredential for the same user which can open the link in the browser.
I moved developing to the ssrs machine itself ( it has vs2008 on it)
so now i'm on the ssrs machine, logged on as user A, starting a webpage, create a webrequest with the same credentials as i'm currently logged on with to the ssrs machine (user A).... and get a 401.
What i don't know is what is giving me the 401. Is it the webserver denying me, or is it ssrs itself (i'm a newbee at ssrs so i don't know much about rights on reports in ssrs itself, but as i said: my logon credentials are the same as the webrequest credentials: user A).
i've googled a lot and tried 5 solutions, but no luck so far.
This won't work if NTLM credentials are required:
webrequest.Credential = new networkcredential ("","","");
You can try the following but it likely will not work:
webrequest.Credentials = CredentialCache.DefaultNetworkCredentials;
Chances are you will need to pass in the actual credentials like:
NetworkCredential networkCredential = new NetworkCredential(UserName, Password, Domain);
CredentialCache credCache = new CredentialCache();
credCache.Add(new Uri(url), "NTLM", networkCredential);
webrequest.Credentials = credCache;
SSRS will need to authentic the WebRequest and default/blank credentials cannot be passed in.
This reminded me of something I ran into a couple years ago:
http://support.microsoft.com/kb/896861
I'm not sure how likely this problem is, but I really think it's worth implementing "Method 2" from that support article (a simple registry addition) just to see if that resolves the problem. (Yes, the article lists a bunch of old OS versions, but I successfully used this on a bunch of SharePoint 2007 servers to resolve problems.)
Worth a try, I think...
I always set
WebRequest.UseDefaultCredentials = True
Then I run the app as the user accessing the SSRS server.
At first I suggest installing Fiddler Web Debugger on the machine where the calling application is run. This way you can see exactly the requests and responses that are made between your application and the SSRS. You might find something like an ISA proxy wanting you to additionally authenticate to it.
Assuming your caller is a console or WebForms application, the following code passes the credentials under which your application runs to the SSRS:
WebRequest webRequest = WebRequest.Create(url);
HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;
// request authentication
httpWebRequest.UseDefaultCredentials = true;
// which is the same as
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
// optional proxy authentication
httpWebRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;

Getting 404 Not Found connecting to webDAV

I am trying to connect to a secure webDAV folder and download a file. I am having problems just trying to get a response from the server and as it keeps giving me a 404 Not Found error as soon as I call Request.GetResponse(). I can connect to the webDAV folder using Windows Explorer by mapping a drive but cannot seem to do this in code. I have looked at other post on this site and others online but most seem to concentrate on connecting to Outlook. Has anybody else had this issue? The code I am using is as follows:
string URI = "https://transfer.mycompany.com/myDirectory/myFile.csv";
string username = "username";
string password = "password";
Request = (HttpWebRequest) WebRequest.Create(URI);
Request.Credentials = new NetworkCredential(username, password);
Request.Method = WebRequestMethods.Http.Get;
Request.Headers.Add("Translate", "f");
Response = (HttpWebResponse) Request.GetResponse();
contentLength = Convert.ToInt64(Response.GetResponseHeader("Content-Length"));
Use the Fiddler tool to see what else headers are sent to the server, when you access it from Windows Explorer. Try adding these headers to your code to make it more similar to the request sent by WindowsExplorer and see if this helps.

Interacting with google appengine from C#

I'm writing a google appengine application, which stores data and has a web front end. I want to be ableto pull down this data in a C# program. This means I need to authenticate with the site (users must be logged in to view the data). How can I authenticate like this? I tried setting credentials on the WebClient but I keep getting the google login page.
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
//should it be username#gmail.com ??
client.BaseAddress = "http://nosoperor-internal.appspot.com";
String s = client.DownloadString("/bank");
//s now contains the google login page, unfortunately
I found an answer in this blog:
Accessing authenticated Google App Engine services from a .NET CF client
and it works ^^
AFAIK, you need to probably use Google Data protocols and account APIs to authenticate.
Edit: I would download the .Net client library and try the examples in there. This is a copy paste from the docs:
Service service = new Service("cl", "exampleCo-exampleApp-1"));
// Set your credentials:
service.setUserCredentials("jo#gmail.com", "mypassword");

Categories

Resources