Helper methods for OpenSAML

During my work with OpenSAML I have created a few helper methods to make it easier to do common things in OpenSAML such as object creation and logging of SAML XML. I my code samples I keep this in the SAMLUtil class.

Creating SAML objects

OpenSAML has a bit complex way of creating SAML objects using a factory pattern.

The normal way to create a SAML object is like this.

1XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
3Assertion assertion = (Assertion)builderFactory
4      .getBuilder(Assertion.DEFAULT_ELEMENT_NAME)
5      .buildObject(Assertion.DEFAULT_ELEMENT_NAME);

Normally the default name of the class is used so it seams redundant to write this out all the time. With generics in JavaSE6 we can make this a lot easier.

1public static <T> T createSAMLObject(final Class<T> clazz) {
2 XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
4 QName defaultElementName = (QName)clazz.getDeclaredField("DEFAULT_ELEMENT_NAME").get(null);
5 T object = (T)builderFactory.getBuilder(defaultElementName).buildObject(defaultElementName);
7return object;

By putting something like this in a utility class we can now create our SAML objects like this

1Assertion assertion = UtilityClass.createSAMLObject(Assertion.class);


The ability to in a nice way log the raw SAML messages i also very important, so I created my own logging method in a utility class. But after using it for a while I learned that I don't have to.

The ability to log the raw SAML messages turns out to be very important for debugging and understanding what messages are flowing. The OpenSAML library uses the log4j logging framework. By setting the threshold level, of the OpenSAML package to debug in the log4j properties file, you get all of the SAML messages to and from your application in your log file. You also get other useful information, so log4j is a good way to go.

If you would like to log just some SAML messages in you code. I have created a message to pretty print SAML elements as XML.

 1public static void logSAMLObject(final XMLObject object) {
 3 Element element = null;
 4 if (object instanceof SignableSAMLObject && ((SignableSAMLObject) object).isSigned()
 5   && object.getDOM() != null) {
 6  element = object.getDOM();
 7 } else {
 8  try {
 9   Marshaller out = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object);
10   out.marshall(object);
11   element = object.getDOM();
12  } catch (MarshallingException e) {
13   logger.error(e.getMessage(), e);
14  }
15 }
16 String xmlString = SerializeSupport.prettyPrintXML(element);