@Override
protected void doEncode(MessageContext messageContext) throws MessageEncodingException {
if (!(messageContext instanceof SAMLMessageContext)) {
log.error("Invalid message context type, this encoder only support SAMLMessageContext");
throw new MessageEncodingException(
"Invalid message context type, this encoder only support SAMLMessageContext");
}
if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) {
log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
throw new MessageEncodingException(
"Invalid outbound message transport type, this encoder only support HTTPOutTransport");
}
// Contains the message body
SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;
SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage();
if (samlMessage == null) {
throw new MessageEncodingException("No outbound SAML message contained in message context");
}
// Add RelayState SOAP header if required
if (samlMsgCtx.getRelayState() != null) {
SOAPHelper.addHeaderBlock(samlMsgCtx, getRelayState(samlMsgCtx.getRelayState()));
}
signMessage(samlMsgCtx);
// Contains the entire envelope with any specified headers, but no body
XMLObject outboundEnveloppe = samlMsgCtx.getOutboundMessage();
Envelope envelope = buildPAOSMessage(samlMessage, outboundEnveloppe);
Element envelopeElem = marshallMessage(envelope);
try {
HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport();
HTTPTransportUtils.addNoCacheHeaders(outTransport);
HTTPTransportUtils.setUTF8Encoding(outTransport);
HTTPTransportUtils.setContentType(outTransport, "text/xml");
outTransport.setHeader("SOAPAction", "http://www.oasis-open.org/committees/security");
Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8");
XMLHelper.writeNode(envelopeElem, out);
out.flush();
} catch (UnsupportedEncodingException e) {
log.error("JVM does not support required UTF-8 encoding");
throw new MessageEncodingException("JVM does not support required UTF-8 encoding");
} catch (IOException e) {
log.error("Unable to write message content to outbound stream", e);
throw new MessageEncodingException("Unable to write message content to outbound stream", e);
}
}