ePrivacy and GPDR Cookie Consent by Cookie Consent

Convenience methods for OpenSAML

Creating SAML objects

This is implementations of some of the methods in the SAMLUtil class referenced in other examples.

OpenSAML has a bit struggling way to create 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 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 definitely the way to go.