How can I read a secure XML URI in C#? - c#

I am trying to read a secure XML document from a URI in C#. I understand the basics of the XmlReader class. However I cannot figure out how to supply a username and password for the URI in code. I get the feeling it has something to do with an XmlSecureResolver object. But I can't figure out how to set the username and password. Can anyone help me with how to set the credentials?
Thanks,
Corey

I think this should do the trick:
WebRequest request = WebRequest.Create(url);
request.Credentials = new NetworkCredential("usernamne", "password");
using (WebResponse response = request.GetResponse())
{
using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
{
// Blah blah...
}
}

A quick Google of the term "XmlReader Authenticate" yields this as the first result:
http://msdn.microsoft.com/en-us/library/47as68k4%28v=vs.71%29.aspx
When resolving a URL to a file that contains the XML data to read, the file may have a restricted access policy. If authentication is required to access a network resource, use the XmlResolver.Credentials property to specify the necessary credentials. If the XmlResolver.Credentials property is not set, then credentials are set to null.
XmlTextReader rdr = new XmlTextReader("http://localhost/bookstore/books.xml");
rdr.XmlResolver.Credentials = CredentialCache.DefaultCredentials;
XmlDocument doc = new XmlDocument();
doc.Load(rdr)
and using different credentials:
NetworkCredential myCred = new NetworkCredential(UserName, SecurelyStoredPassword, domain);
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri("www.contoso.com"), "Basic", myCred);
myCache.Add(new Uri("app.contoso.com"), "Basic", myCred);
reader.XmlResolver.Credentials = myCache;

Related

Check credential before requesting the Web Service

For a WebService, How can I check the credential before requesting the WebService?
In this exemple we are using a bad password to simulate a HTTP 401 : Unauthorized..
Is there a way before the var param = DoComplexeWork(); to validate the credential?
string UserName = "FOOBAR_USR";
string SecurelyStroredPassword = "FOOBAR_BAD_PWD";
string Domain = "FOOBAR_DOM";
string Url = "https://example.com/Foo/Bar.svc";
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(
new Uri(Url),
"Basic",
new NetworkCredential(UserName, SecurelyStroredPassword, Domain)
);
var iFoo = new MyFooBarWebService();
iFoo.Credentials = credentialCache;
//Check if Credential is OK
var param = DoComplexeWork();
var result = iFoo.CreateBar(param);
Validating the credentials are made on each request. So you need another URL to request that only validates the credentials.
Depending on your webservice you might be able to make a HEAD request. But that may or may not trigger the actual processing as well.
So there is no obvious easy way to do this, because of the underlying HTTP protocol.

Get file list from owncloud

I want to get file list from owncloud on my ASP site. I was succeed using
curl -X PROPFIND -u user:password "http://yourserver.com/owncloud/remote.php/webdav/" from linux but I can't get the same result using default http request with propfind type in order to use it then in c# https://user:password#host/owncloud/remote.php/webdav. I get 400 code as a result on my request. Also I tried webdavclient from nuget but received method not allowed exception.
IClient c = new Client(new NetworkCredential { UserName = "user", Password = "password" });
var client = new WebDAVClient.Client(new NetworkCredential());
c.Server = "xxx.com/owncloud/remote.php/webdav/";
var isfolderCreated = c.CreateDir("/", "lalala").Result;
Could anybody say to me how to send http request to owncloud to get the file list? I tried webdav protocol that is used by clients but maybe I should try anything else?
I found the issue that prevented me. I just didn't use basic authorization correctly in http request. Since I add correct credentials I could send the http request and get the response. And here is the code I use in c#:
var request = (HttpWebRequest)WebRequest.Create("xxx.com/owncloud/remote.php/webdav/");
request.Credentials = new NetworkCredential("user", "password");
request.PreAuthenticate = true;
request.Method = #"PROPFIND";
request.Headers.Add(#"Translate", "F");
var httpGetResponse = (HttpWebResponse)request.GetResponse();
using (var responseStream = httpGetResponse.GetResponseStream())
{
long responseLength = httpGetResponse.ContentLength;
using (var streamReader = new StreamReader(responseStream, Encoding.UTF8))
{
var files = XElement.Parse(streamReader.ReadToEnd());
streamReader.Close();
}
responseStream.Close();
}

Cannot connect to url in C# with 401 unauthorized error

I'm looking to get the content of a page from
http://12.18.60.199:81
I'm using my corporate network and if I use internet explorer, it prompts for username and password, I type that in and I get the content of the page. I need to do this in C#, but have no luck for the past few hours:
Uri requestUri = null;
Uri.TryCreate("http://12.18.60.199:81", UriKind.Absolute, out requestUri);
NetworkCredential nc = new NetworkCredential(#"username", #"password", "domain");
CredentialCache cache = new CredentialCache();
cache.Add(requestUri, "Basic", nc); //also tried "Anonymous", "Basic", "Digest", "Dpa",
//"External", "Kerberos", "Msn", "Negotiate", "Ntlm", "Sicily"
using (WebClient client = new WebClient())
{
client.Credentials = cache;
using (Stream stream = client.OpenRead("http://12.18.60.199:81"))
using (StreamReader reader = new StreamReader(stream))
{
//stuff
}
}
Keep getting 401 unauthorized, invalid credentials, help!
If I substitute the above address with http://google.com, it'll work, so the code works... username and password have been tested to work in broswer
If you are connecting through a proxy server try adding in your proxy and pass the credentials. For example:
// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://www.test.com");
// proxy details
myRequest.Proxy = new WebProxy("http://10.0.0.1", true);
myRequest.Proxy.Credentials = new NetworkCredential("test", "password", "domain");
I had same issue, and found workaround to add Authorization request header. I've used fiddler to get that base64. Never found proper solution, as you all know temp solutions are long-lasting in out world :)
service.Url = "http://127.0.0.1/";
service.SetRequestHeader("Authorization", "Basic dW8sX3NvYXB6SjRma2pzdXZqNDg5ZA==");
service.PreAuthenticate = true;

Cookies are not retaining any data while sent as part of a WebRequest

This is how I am setting up the cookies data and passing along web request. When I check the response from the website using fiddler I see cookies have no data and expiry data is set to Jan 1, 1900. Any help would be much appreciated. Please let me know if something is not clear from following code or you need more info to answer my question. Thanks.
System.Net.Cookie userType =
new System.Net.Cookie("CUserType","subscriber", "/", "www.DOMAIN_NAME.com");
userType.Expires = DateTime.Now.AddYears(1);
System.Net.Cookie dUserType =
new System.Net.Cookie("dCUserType", "subscriber", "/", "www.DOMAIN_NAME.com");
dUserType.Expires = DateTime.Now.AddYears(1);
System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
cookieContainer.Add(userType);
cookieContainer.Add(dUserType);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL);
webRequest.Proxy = new WebProxy("127.0.0.1", 8888);
webRequest.Referer = "http://DOMAIN_NAME/search/index.aspx?lid=3";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Date = DateTime.Now;
webRequest.CookieContainer = cookieContainer;
string result;
using (var stream = webRequest.GetResponse().GetResponseStream())
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
When you set cookies, you also need to set the domain because the cookies are different for www.domain.com and just domain.com.
To make them the same, you need to set the domain on your cookie.
First on the web.config
<authentication mode="Forms">
<forms domain="yoururl.com" ... />
</authentication>
and second when you set manually your cookies (with out the www.):
Response.Cookies[cookieName].Domain = "yoururl.com";
or as you set it up (with out the subdomain www.):
System.Net.Cookie dUserType =
new System.Net.Cookie("dCUserType", "subscriber", "/", "DOMAIN_NAME.com");
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Lost session/cookie when login as another user

Proxy in .net

I tried accessing web for xml parsing using the code below:
System.Uri proxy = new System.Uri("http://usr:pwd#10.1.121.2:8080");
System.Net.WebRequest.DefaultWebProxy = new System.Net.WebProxy(proxy);
string url = "http://url/";
XmlTextReader reader = new XmlTextReader(url);
richTextBox1.Text = Convert.ToString(reader.Read());
But it's giving an error that proxy authentication needed. I have set the proxy parameters already. So can someone suggest changes needed to make it work?
WebProxy proxy = new WebProxy("172.0.0.1:8080", true);
proxy.Credentials = new NetworkCredential("user", "passw", "domain");
Then, use WebRequest to retrieve the data stream through the proxy.
WebRequest dstream = WebRequest.Create("http://data-stream-url.com/file.ext");
dstream.Proxy = proxy;
You'll have to set Credentials property on the WebRequest.DefaultWebProxy object. CredentialCache.DefaultNetworkCredentials might do the job.

Categories

Resources