Is it possible to get the current network credentials?
i like to get a website programmaticaly with the WebClient object and use the current credentials
(iis integrated windows authentication)
but the username only doesn't help...
the WebClient needs an ICredential object
can I retrieve the current user credential or
is it possible to get the password of the user? (I dont think, its possible...)
my code:
WebClient wc = new WebClient();
// todo: instead of "new NetworkCredential()" the current user credential
wc.Credentials = new NetworkCredential("user", "pass");
After two hours of debugging the HTTP headers with Ethereal and comparing the browser request/response stream vs the .NET stream, I finally solved it!
I did some googling and found other people with the same symptoms, i.e. you cannot use HttpWebRequest with automatic redirects enabled to do a login process involving 302s and cookies because the cookies don't get set until the end of the whole process.
The solution was to disable auto redirects and implement the whole login process manually on a step-by-step basis (get the 'Location' header of 302 redirect responses, as well as the 'Set-cookie' header, and pass these down to successive steps as needed).
I tried using a CookieContainer to handle the cookies automarically but that didn't work either. Reading the 'Cookie' and 'Set-Cookie' headers directly did the trick though.
This error can occur when an application performs a web request to a web app that's trying to interogate the Request.UserAgent - but the requesting app has not set the user agent in the request.
To resolve either set the user agent before sending the request eg:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(theUrl);
req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
Alternatively, and preferrably (if you have access to it), fix the server side web application to check Request.UserAgent for null or blank values before performing any operations on it.
=================
I've never known such kinda error before, ant I recommend you post a new thread on this issue.
//create a cookie container to hold the cookie
//this will override the header is you try to set cookie directly
//if you do not pass up a cookie container,
//the response will not fill out the cookie collection
Cookie c =
new Cookie();
CookieContainer cc =
new CookieContainer();
//int i;
//for (i = 0; i < HttpContext.Current.Request.Cookies.Count - 1; i++)
//{
// c.Name = HttpContext.Current.Request.Cookies[i].Name;
// c.Value = HttpContext.Current.Request.Cookies[i].Value;
// c.Domain = request.RequestUri.Host;
// //c.Domain = urlAddr.Substring(urlAddr.IndexOf(".") + 1);
// c.Expires = DateTime.Now.AddYears(1);
// cc.Add(c);
// request.CookieContainer = cc;
//}
request.CookieContainer = cc;
//The WebResponse object gets the Request's response (the HTML)
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Now dump the contents of our HTML in the Response object to a Stream reader
using (StreamReader sr =
new StreamReader(response.GetResponseStream()))
{
//And dump the StreamReader into a string...
result = sr.ReadToEnd();
//Close and clean up the StreamReader
sr.Close();
}
result = result.Replace("/test",response.ResponseUri.Scheme +"://"+ response.ResponseUri.Host +
"/test");
return result;
Hello, I just tried the sample with "CredentialCache.DefaultNetworkCredentials" but this Crededential is Empty and not Correct.
Generally i think this is not the right solution? I don't want to use the Credential Cache (only if i have to, and not the default, i just would like to receive the current credentials).
What i want is to connect to a sharepoint WebService, so i try to give them the credentials Im actually logged in.
I've been googling this all day. What I found was that you should be able to use CredentialCache.DefaultCredentials, and it'll work.
It doesn't.
What I have is a WCF service hosted in IIS. No impersonation is used, so it should be running as the user as configured in the Application Pool. Indeed, if I examine System.Security.Principal.WindowsIdentity.GetCurrent(), I see that user.
In this service method, I try to get a file from a SharePoint document list by URL, which happens to be an HTTPS link. Authentication is handled by an ISA server. The three lines of code of interest are as follows:
This code gets a 401 Unauthorized error every time. Now, the weird thing is, if instead of UseDefaultCredentials, or client.Credentials = CredentialCache.DefaultCredentails, or client.Credentials = CredentialCache.DefaultNetworkCredentials (all of which
fail), I do this:
client.Credentials = new System.Net.NetworkCredential(username, password, domain);
Where username/password/domain describe the exact same account as the current Windows identity, the identity running the Application Pool, it works just fine.
So the question I have is: Why, if the current identity is perfectly valid, does DefaultCredentials not work?
I even went so far as to wrap the code in a WindowsImpersonationContext context = WindowsIdentity.GetCurrent().Impersonate() block to force the code to run as the current identity (?), but that wasn't good enough either.
One would think this could be solved if you could simply obtain the credentials from a given identity object, except so far, everything I've found says you do this by impersonating said identity and using DefaultCredentials, which I've just proven to myself
over and over again doesn't work. [:@]
mischa
Member
48 Points
17 Posts
Get Current NetworkCredential
Aug 14, 2006 07:50 AM|LINK
Is it possible to get the current network credentials?
i like to get a website programmaticaly with the WebClient object and use the current credentials
(iis integrated windows authentication)
thank you
lostlander
Contributor
3041 Points
607 Posts
Re: Get Current NetworkCredential
Aug 15, 2006 04:41 AM|LINK
Hope the codes below help you.
IIdenttiy winid= HttpContext.Current.User.Identity;
WindowsIdentity wi = (WindowsIdentity)WinId;
or
WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
and retrieve domain\user:
string user = wi.Name;
mischa
Member
48 Points
17 Posts
Re: Get Current NetworkCredential
Aug 15, 2006 06:22 AM|LINK
but the username only doesn't help...
the WebClient needs an ICredential object
can I retrieve the current user credential or
is it possible to get the password of the user? (I dont think, its possible...)
my code:
WebClient wc = new WebClient();
// todo: instead of "new NetworkCredential()" the current user credential
wc.Credentials = new NetworkCredential("user", "pass");
lostlander
Contributor
3041 Points
607 Posts
Re: Get Current NetworkCredential
Aug 16, 2006 03:37 AM|LINK
How about this:
1, using System.Net;
2, NetworkCredential cred = CredentialCache.DefaultNetworkCredentials;
mischa
Member
48 Points
17 Posts
Re: Get Current NetworkCredential
Aug 16, 2006 05:44 AM|LINK
in asp.net I recieve a server error: Too many automatic redirections were attempted.
lostlander
Contributor
3041 Points
607 Posts
Re: Get Current NetworkCredential
Aug 16, 2006 06:26 AM|LINK
Wierd error!
I've done some search for you.
Here are some quotes:
Kufu:
http://forums.whirlpool.net.au/forum-replies-archive.cfm/491772.html
After two hours of debugging the HTTP headers with Ethereal and comparing the browser request/response stream vs the .NET stream, I finally solved it!
I did some googling and found other people with the same symptoms, i.e. you cannot use HttpWebRequest with automatic redirects enabled to do a login process involving 302s and cookies because the cookies don't get set until the end of the whole process.
The solution was to disable auto redirects and implement the whole login process manually on a step-by-step basis (get the 'Location' header of 302 redirect responses, as well as the 'Set-cookie' header, and pass these down to successive steps as needed).
I tried using a CookieContainer to handle the cookies automarically but that didn't work either. Reading the 'Cookie' and 'Set-Cookie' headers directly did the trick though.
Tim:
http://geekswithblogs.net/TimH/
This error can occur when an application performs a web request to a web app that's trying to interogate the Request.UserAgent - but the requesting app has not set the user agent in the request.
To resolve either set the user agent before sending the request eg:
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(theUrl);req.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
Alternatively, and preferrably (if you have access to it), fix the server side web application to check Request.UserAgent for null or blank values before performing any operations on it.
=================
I've never known such kinda error before, ant I recommend you post a new thread on this issue.
Regards,
lostlander.
mischa
Member
48 Points
17 Posts
Re: Get Current NetworkCredential
Aug 16, 2006 06:37 AM|LINK
I found the same in google...
but I dont unterstand why the same code works in a console app
I also tried to write a class library... it includes one static function that makes a connect to a website and gives back the content as a string..
if I use this assembly in a console app, it works fine
in an asp.net application I get always this "too many automatic redirections..." error
spacejang
Member
155 Points
31 Posts
Re: Get Current NetworkCredential
Aug 23, 2006 07:37 PM|LINK
I had the same problem as you."Too many automatic redirections were attempted. "
But my site now it works..
public static class HtmlScraper{
/// <summary> /// Return the html page of URL. /// </summary> /// <param name="urlAddr">urlAddr</param> /// <returns>result</returns> public static string GetHtml(string urlAddr){
if (string.IsNullOrEmpty(urlAddr)){
throw new ArgumentNullException("urlAddr");}
string result; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(urlAddr));
//create a cookie container to hold the cookie //this will override the header is you try to set cookie directly //if you do not pass up a cookie container, //the response will not fill out the cookie collection Cookie c = new Cookie(); CookieContainer cc = new CookieContainer(); //int i; //for (i = 0; i < HttpContext.Current.Request.Cookies.Count - 1; i++) //{ // c.Name = HttpContext.Current.Request.Cookies[i].Name; // c.Value = HttpContext.Current.Request.Cookies[i].Value; // c.Domain = request.RequestUri.Host; // //c.Domain = urlAddr.Substring(urlAddr.IndexOf(".") + 1); // c.Expires = DateTime.Now.AddYears(1); // cc.Add(c); // request.CookieContainer = cc; //}request.CookieContainer = cc;
//The WebResponse object gets the Request's response (the HTML) HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //Now dump the contents of our HTML in the Response object to a Stream reader using (StreamReader sr = new StreamReader(response.GetResponseStream())){
//And dump the StreamReader into a string...result = sr.ReadToEnd();
//Close and clean up the StreamReadersr.Close();
}
result = result.Replace("/test",response.ResponseUri.Scheme +"://"+ response.ResponseUri.Host + "/test"); return result;}
}
Cisjokey
Member
9 Points
11 Posts
Re: Get Current NetworkCredential
Feb 26, 2008 01:38 PM|LINK
Hello, I just tried the sample with "CredentialCache.DefaultNetworkCredentials" but this Crededential is Empty and not Correct.
Generally i think this is not the right solution? I don't want to use the Credential Cache (only if i have to, and not the default, i just would like to receive the current credentials).
What i want is to connect to a sharepoint WebService, so i try to give them the credentials Im actually logged in.
Can somebody help me please?
Thank you
YakkoWarner
Member
8 Points
6 Posts
Re: Get Current NetworkCredential
Apr 18, 2008 08:20 PM|LINK
I've been googling this all day. What I found was that you should be able to use CredentialCache.DefaultCredentials, and it'll work.
It doesn't.
What I have is a WCF service hosted in IIS. No impersonation is used, so it should be running as the user as configured in the Application Pool. Indeed, if I examine System.Security.Principal.WindowsIdentity.GetCurrent(), I see that user.
In this service method, I try to get a file from a SharePoint document list by URL, which happens to be an HTTPS link. Authentication is handled by an ISA server. The three lines of code of interest are as follows:
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
Stream stream = client.OpenRead(url);
This code gets a 401 Unauthorized error every time. Now, the weird thing is, if instead of UseDefaultCredentials, or client.Credentials = CredentialCache.DefaultCredentails, or client.Credentials = CredentialCache.DefaultNetworkCredentials (all of which fail), I do this:
client.Credentials = new System.Net.NetworkCredential(username, password, domain);
Where username/password/domain describe the exact same account as the current Windows identity, the identity running the Application Pool, it works just fine.
So the question I have is: Why, if the current identity is perfectly valid, does DefaultCredentials not work?
I even went so far as to wrap the code in a WindowsImpersonationContext context = WindowsIdentity.GetCurrent().Impersonate() block to force the code to run as the current identity (?), but that wasn't good enough either.
One would think this could be solved if you could simply obtain the credentials from a given identity object, except so far, everything I've found says you do this by impersonating said identity and using DefaultCredentials, which I've just proven to myself over and over again doesn't work. [:@]