Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Supplying Authentication Credentials to XmlResolver when Reading from a File

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.

For example, assume that credentials are needed when requesting data from the Web for authentication purposes. If the Web virtual directory allows anonymous access, then the property does not need to be set for anonymous access. However, if the directory does not allow anonymous access, then you need to supply credentials. The following example shows the credentials being set on XmlTextReader to access the directory http://localhost/bookstore/inventory.xml.

Dim rdr As New XmlTextReader("http://localhost/bookstore/book.xml")
rdr.XmlResolver.Credentials = CredentialCache.DefaultCredentials
Dim doc as new XmlDocument()
doc.Load(rdr)
[C#]
XmlTextReader rdr = new XmlTextReader("http://localhost/bookstore/books.xml");
rdr.XmlResolver.Credentials = CredentialCache.DefaultCredentials;
XmlDocument doc = new XmlDocument();
doc.Load(rdr);

Different credentials can be supplied for different URIs and added to a credential cache. These credentials are used to check authentication for the different URIs regardless of the original source of the XML. The following example shows adding credentials to a cache.

Dim myCred As New NetworkCredential(UserName, SecurelyStoredPassword, domain)
Dim myCache As New CredentialCache()
myCache.Add(New Uri("www.contoso.com"), "Basic", myCred)
myCache.Add(New Uri("app.contoso.com"), "Basic", myCred)
reader.XmlResolver.Credentials = myCache
   ...
[C#]
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;
   ...

The XmlDocument has an XmlResolver property that is used to set an XmlResolver with the correct credentials to allow access to external resources. For more information, see XmlDocument.XmlResolver Property. For information on the NetworkCredential class, see NetworkCredential Class.

For information on creating credentials to access XML Web services, see Securing XML Web Services Created Using ASP.NET.

See Also

Resolve External XML Resources Named by a URI | Resolving Resources using the XmlResolver | Creating a Custom Resolver

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft