简体   繁体   中英

Best way to get XML signature using JAXB

I'm using REST and XML for communication between client and server. The client adds an enveloped signature to every xml and the server needs to verify its authentication. I'm using JAXB for marshalling and unmarshalling. I need to get the signature element as org.w3c.dom.Element to verify it and I want to avoid using straight DOM manipulation. The server also needs to sign the response XML.

Let's look at some code:

REST interface

getXML(Root root)

XML:

<root>
  <foo></foo>
  <bar></bar>
  <Signature Id="Signature-1c7757b0" xlns="http://www.w3.org/2000/09/xmldsig#">
      ...
  </Signature> 
<root>

This is my current solution.

JAXB class

@XmlRootElement
public class Root{

   @XmlElement
   private Foo foo;

   @XmlElement
   private Bar bar;

   @XmlAnyElement(lax = true)
   private List<Element> signature;

}

Can anyone think of a better solution to handle this? I didn't find a lot of help online specifically detailing how to work with the DSig library and JAXB.

I'm not sure if I understand you correctly but if you need to extract Signature you can use stax. I do so with spring batch jobs.

I have following beans:

@Bean
public StaxEventItemReader<Catalog.Products.Product> nexwayCatalogReader() {
    return Try.ofFailable(() -> {
        final StaxEventItemReader<Catalog.Products.Product> itemReader = new StaxEventItemReader<>();
        itemReader.setResource(new UrlResource(nexwaySettings.getEndpoints().getXmlCatalogUrl()));
        itemReader.setFragmentRootElementName("product");
        itemReader.setUnmarshaller(productMarshaller());
        return itemReader;
    }).orElseThrow(() -> new RuntimeException("Unable to create resource using nexwayCatalogUrl = ["
                            + nexwaySettings.getEndpoints().getXmlCatalogUrl() + "]"));
}

@Bean
public Jaxb2Marshaller productMarshaller() {
    final Jaxb2Marshaller productMarshaller = new Jaxb2Marshaller();
    productMarshaller.setMappedClass(Catalog.Products.Product.class);
    productMarshaller.setClassesToBeBound(Catalog.Products.Product.class);
    return productMarshaller;
}

So the reader reads only the part of xml I need (products). Xml element product is being mapped to class instance.

BTW sax / stax seems to be better idea than standard Unmarshaller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM