这是关于在使用JAXB API时避免XXE攻击。我知道在使用JAXB时,可以覆盖默认解析机制,可以使用备用SAX解析器并设置实体功能以避免XXE攻击。但是想了解默认解析器到底是什么,并在其上设置安全功能。有什么帮助吗?
您可以通过使用JAXB和禁用外部实体支持的StAX解析器来执行以下操作:
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("input.xml"));
Customer customer = (Customer) unmarshaller.unmarshal(xsr);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}