Java Code Examples for org.opensaml.common.binding.SAMLMessageContext#getOutboundSAMLMessage()

The following examples show how to use org.opensaml.common.binding.SAMLMessageContext#getOutboundSAMLMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseSAML1MessageEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the response URL from the relying party endpoint. If the SAML message is a {@link Response} and the relying
 * party endpoint contains a response location then that location is returned otherwise the normal endpoint location
 * is returned.
 * 
 * @param messageContext current message context
 * 
 * @return response URL from the relying party endpoint
 * 
 * @throws MessageEncodingException throw if no relying party endpoint is available
 */
protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException {
    Endpoint endpoint = messageContext.getPeerEntityEndpoint();
    if (endpoint == null) {
        throw new MessageEncodingException("Endpoint for relying party was null.");
    }

    URLBuilder urlBuilder;
    if (messageContext.getOutboundSAMLMessage() instanceof Response
            && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) {
        urlBuilder = new URLBuilder(endpoint.getResponseLocation());
    } else {
        if (DatatypeHelper.isEmpty(endpoint.getLocation())) {
            throw new MessageEncodingException("Relying party endpoint location was null or empty.");
        }
        urlBuilder = new URLBuilder(endpoint.getLocation());
    }
    
    if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){
       throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); 
    }
    return urlBuilder;
}
 
Example 2
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populate the Velocity context instance which will be used to render the POST body.
 * 
 * @param velocityContext the Velocity context instance to populate with data
 * @param messageContext the SAML message context source of data
 * @param endpointURL endpoint URL to which to encode message
 * @throws MessageEncodingException thrown if there is a problem encoding the message
 */
protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext,
        String endpointURL) throws MessageEncodingException {
    
    Encoder esapiEncoder = ESAPI.encoder();

    String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL);
    log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL);
    velocityContext.put("action", encodedEndpointURL);
    velocityContext.put("binding", getBindingURI());

    log.debug("Marshalling and Base64 encoding SAML message");
    if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
        marshallMessage(messageContext.getOutboundSAMLMessage());
    }
    try {
        String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
        String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
        if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
            velocityContext.put("SAMLRequest", encodedMessage);
        } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
            velocityContext.put("SAMLResponse", encodedMessage);
        } else {
            throw new MessageEncodingException(
                    "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
        }
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
        throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported");
    }

    String relayState = messageContext.getRelayState();
    if (checkRelayState(relayState)) {
        String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(relayState);
        log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState);
        velocityContext.put("RelayState", encodedRelayState);
    }
}
 
Example 3
Source File: HandlerChainAwareHTTPSOAP11Encoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Perform final binding-specific processing of message context and prepare it for encoding
 * to the transport.  
 * 
 * <p>
 * This should include constructing and populating all binding-specific structure and data that needs to be
 * reflected by the message context's properties.
 * </p>
 * 
 * <p>
 * This method is called prior to {@link #processOutboundHandlerChain(MessageContext)}.
 * </p>
 * 
 * @param messageContext the message context to process
 * @throws MessageEncodingException thrown if there is a problem preparing the message context
 *              for encoding
 */
protected void prepareMessageContext(MessageContext messageContext) throws MessageEncodingException {
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (samlMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }

    signMessage(samlMsgCtx);

    log.debug("Building SOAP envelope");

    Envelope envelope = envBuilder.buildObject();
    Body body = bodyBuilder.buildObject();
    envelope.setBody(body);
    body.getUnknownXMLObjects().add(samlMessage);

    messageContext.setOutboundMessage(envelope);
}
 
Example 4
Source File: BaseSAML2MessageEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the response URL from the relying party endpoint. If the SAML message is a {@link StatusResponseType} and the relying
 * party endpoint contains a response location then that location is returned otherwise the normal endpoint location
 * is returned.
 * 
 * @param messageContext current message context
 * 
 * @return response URL from the relying party endpoint
 * 
 * @throws MessageEncodingException throw if no relying party endpoint is available
 */
protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException {
    Endpoint endpoint = messageContext.getPeerEntityEndpoint();
    if (endpoint == null) {
        throw new MessageEncodingException("Endpoint for relying party was null.");
    }
    
    URLBuilder urlBuilder;
    if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType
            && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) {
        urlBuilder = new URLBuilder(endpoint.getResponseLocation());
    } else {
        if (DatatypeHelper.isEmpty(endpoint.getLocation())) {
            throw new MessageEncodingException("Relying party endpoint location was null or empty.");
        }
        urlBuilder = new URLBuilder(endpoint.getLocation());
    }
    
    if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){
       throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); 
    }
    return urlBuilder;
}
 
Example 5
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public VelocityContext encodeMsgContext(MessageContext messageContext)
		throws MessageEncodingException {


	SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

	SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
	if (outboundMessage == null) {
		throw new MessageEncodingException(
				"No outbound SAML message contained in message context");
	}

	signMessage(samlMsgCtx);
	samlMsgCtx.setOutboundMessage(outboundMessage);

	return encodeMsgContext(samlMsgCtx);
}
 
Example 6
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
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");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (outboundMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }
    String endpointURL = getEndpointURL(samlMsgCtx).buildURL();

    if (samlMsgCtx.getOutboundSAMLMessage() instanceof ResponseAbstractType) {
        ((ResponseAbstractType) samlMsgCtx.getOutboundSAMLMessage()).setRecipient(endpointURL);
    }

    signMessage(samlMsgCtx);
    samlMsgCtx.setOutboundMessage(outboundMessage);

    postEncode(samlMsgCtx, endpointURL);
}
 
Example 7
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
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");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (outboundMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }
    String endpointURL = getEndpointURL(samlMsgCtx).buildURL();

    if (samlMsgCtx.getOutboundSAMLMessage() instanceof StatusResponseType) {
        ((StatusResponseType) samlMsgCtx.getOutboundSAMLMessage()).setDestination(endpointURL);
    }

    signMessage(samlMsgCtx);
    samlMsgCtx.setOutboundMessage(outboundMessage);

    postEncode(samlMsgCtx, endpointURL);
}
 
Example 8
Source File: HTTPRedirectDeflateEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes the signature from the protocol message.
 * 
 * @param messageContext current message context
 */
protected void removeSignature(SAMLMessageContext messageContext) {
    SignableSAMLObject message = (SignableSAMLObject) messageContext.getOutboundSAMLMessage();
    if (message.isSigned()) {
        log.debug("Removing SAML protocol message signature");
        message.setSignature(null);
    }
}
 
Example 9
Source File: HTTPRedirectDeflateEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Builds the URL to redirect the client to.
 * 
 * @param messagesContext current message context
 * @param endpointURL endpoint URL to send encoded message to
 * @param message Deflated and Base64 encoded message
 * 
 * @return URL to redirect client to
 * 
 * @throws MessageEncodingException thrown if the SAML message is neither a RequestAbstractType or Response
 */
protected String buildRedirectURL(SAMLMessageContext messagesContext, String endpointURL, String message)
        throws MessageEncodingException {
    log.debug("Building URL to redirect client to");
    URLBuilder urlBuilder = new URLBuilder(endpointURL);

    List<Pair<String, String>> queryParams = urlBuilder.getQueryParams();
    queryParams.clear();

    if (messagesContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
        queryParams.add(new Pair<String, String>("SAMLRequest", message));
    } else if (messagesContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
        queryParams.add(new Pair<String, String>("SAMLResponse", message));
    } else {
        throw new MessageEncodingException(
                "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
    }

    String relayState = messagesContext.getRelayState();
    if (checkRelayState(relayState)) {
        queryParams.add(new Pair<String, String>("RelayState", relayState));
    }

    Credential signingCredential = messagesContext.getOuboundSAMLMessageSigningCredential();
    if (signingCredential != null) {
        // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
        String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
        Pair<String, String> sigAlg = new Pair<String, String>("SigAlg", sigAlgURI);
        queryParams.add(sigAlg);
        String sigMaterial = urlBuilder.buildQueryString();

        queryParams.add(new Pair<String, String>("Signature", generateSignature(signingCredential, sigAlgURI,
                sigMaterial)));
    }

    return urlBuilder.buildURL();
}
 
Example 10
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void populateVelocityContext(VelocityContext velocityContext,
		SAMLMessageContext messageContext) throws MessageEncodingException {

	log.debug("Marshalling and Base64 encoding SAML message");
	if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
		marshallMessage(messageContext.getOutboundSAMLMessage());
	}
	try {
		String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
		String encodedMessage = Base64.encodeBytes(
				messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
		if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
			velocityContext.put("SAMLRequest", encodedMessage);
		} else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
			velocityContext.put("SAMLResponse", encodedMessage);
		} else {
			throw new MessageEncodingException(
					"SAML message is neither a SAML RequestAbstractType or StatusResponseType");
		}
	} catch (UnsupportedEncodingException e) {
		log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
		throw new MessageEncodingException(
				"Unable to encode message, UTF-8 encoding is not supported");
	}

	Credential signingCredential = messageContext.getOuboundSAMLMessageSigningCredential();
	if (signingCredential == null) {
		log.debug("No signing credential was supplied, skipping HTTP-Post simple signing");
		return;
	}

	String sigAlgURI = getSignatureAlgorithmURI(signingCredential, null);
	velocityContext.put("SigAlg", sigAlgURI);

	String formControlData = buildFormDataToSign(velocityContext,messageContext, sigAlgURI);
	velocityContext.put("Signature",generateSignature(signingCredential, sigAlgURI,formControlData));

	KeyInfoGenerator kiGenerator = SecurityHelper.getKeyInfoGenerator(signingCredential, null, null);
	
	if (kiGenerator != null) {
		String kiBase64 = buildKeyInfo(signingCredential, kiGenerator);
		if (!DatatypeHelper.isEmpty(kiBase64)) {
			velocityContext.put("KeyInfo", kiBase64);
		}
	}
}