Partager via


Using the XmlSecureResolver to restrict access to web sites

Having just written an article on XmlResolver and looked through the MSDN docs I realised that there was little in terms of explanation on how to use the XmlSecureResolver. As always code speaks volumes sIo put together this example which shows how the XmlSecureResolver can be used to restrict access to specific web sites. The XmlSecureResolver secures another implementation of an XmlResolver by wrapping the supplied XmlResolver and restricting the resources that it has access to. For instance, the XmlSecureResolver has the ability to prohibit access to particular internet sites or zones.

public static void UsingXmlSecureResolverToAccessURIs()

{

try

{

WebPermission wb = new WebPermission(PermissionState.None);

wb.AddPermission(NetworkAccess.Connect,

@"https://msdn.microsoft.com/xml/rss.xml");

wb.AddPermission(NetworkAccess.Connect,

@"https://www.w3.org/TR/REC-xml/");

PermissionSet ps = new PermissionSet(PermissionState.None);

ps.AddPermission( wb );

XmlTextReader reader = new XmlTextReader

(@"https://msdn.microsoft.com/xml/rss.xml");

reader.XmlResolver = new XmlSecureResolver(new XmlUrlResolver(), ps);

while (reader.Read()) ;

// This call fails as the site is not in the permission set

reader = new XmlTextReader(@"https://msdn.microsoft.com/sql/rss.xml");

reader.XmlResolver = new XmlSecureResolver(new XmlUrlResolver(), ps);

while (reader.Read()) ;

}

catch (Exception e)

{

Console.WriteLine("Unsuccessful Read Access");

Console.WriteLine(e);

}

}

When this code is run, only those URIs added to the WebPermission class are allowed to be accessed by the XmlTextReader. All others are denied and result in a security exception being thrown. This is extremely useful in restricting the sites that can be visited, especially when the list of sites can be constrained with a Regex expression.

Comments

  • Anonymous
    October 21, 2004
    HOW TO RESTRICT TYPES OF INTERNET ACCESS