Pretty printing OpenSAML Objects

In the best of worlds it's not often you need to look into the actual XML of a SAML message. In the real world however, when troubleshooting a problem, there is often leads to be found by looking at the XML of the SAML message.

Lets have a look on how to go about doing that in OpenSAML 4.

First let's create a OpenSAML object so we have something to print.

 1AuthnRequest authnRequest = buildAuthnRequest();
 2
 3private static AuthnRequest buildAuthnRequest() {
 4		AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
 5		authnRequest.setIssueInstant(Instant.now());
 6		authnRequest.setDestination(MESSAGE_RECEIVER_ENDPOINT);
 7		authnRequest.setProtocolBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI);
 8		authnRequest.setAssertionConsumerServiceURL(ASSERTION_CONSUMER_ENDPOINT);
 9		authnRequest.setID(OpenSAMLUtils.generateSecureRandomId());
10		authnRequest.setIssuer(buildIssuer());
11		authnRequest.setNameIDPolicy(buildNameIdPolicy());
12
13		return authnRequest;
14}
15
16private static NameIDPolicy buildNameIdPolicy() {
17	NameIDPolicy nameIDPolicy = OpenSAMLUtils.buildSAMLObject(NameIDPolicy.class);
18	nameIDPolicy.setAllowCreate(true);
19
20	nameIDPolicy.setFormat(NameIDType.TRANSIENT);
21
22	return nameIDPolicy;
23}
24
25private static Issuer buildIssuer() {
26	Issuer issuer = OpenSAMLUtils.buildSAMLObject(Issuer.class);
27	issuer.setValue(ISSUER);
28
29	return issuer;
30}

Next, lets do the magic to convert the object to a string.

1Marshaller out = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest);
2out.marshall(authnRequest);
3Element element = authnRequest.getDOM();
4String xmlString = SerializeSupport.prettyPrintXML(element);
5
6System.out.println(xmlString);

In the snipped above this the OpenSAML XMLObjectProviderRegistrySupport is used to convert the OpenSAML object to a XML element. The OpenSAML SerializeSupport helper class is then used to format the element as a pretty printed indented string.

Get it on Github!

The full sample code is available on Github at https://github.com/rasmusson/OpenSAML-sample-code under opensaml-prettyprint

Just clone it, run it, go nuts!

1git clone https://github.com/rasmusson/OpenSAML-sample-code/
2cd opensaml-prettyprint
3mvn compile exec:java -Dexec.mainClass="no.steras.opensamlSamples.prettyprint.Prettyprint"

The pretty printed object is printed to the console.