Java Code Examples for org.opensaml.saml.common.SAMLObject

The following examples show how to use org.opensaml.saml.common.SAMLObject. These examples are extracted from open source projects. 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
public String handleSsoGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof AuthnRequest)) {
            throw new RuntimeException("Expected AuthnRequest; received: " + messageContext.getMessage());
        }

        AuthnRequest authnRequest = (AuthnRequest) messageContext.getMessage();

        return createSamlAuthResponse(authnRequest);
    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source Project: armeria   Source File: HttpPostBindingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts an {@link AggregatedHttpRequest} which is received from the remote entity to
 * a {@link SAMLObject}.
 */
static <T extends SAMLObject> MessageContext<T> toSamlObject(AggregatedHttpRequest req, String name) {
    final SamlParameters parameters = new SamlParameters(req);
    final byte[] decoded;
    try {
        decoded = Base64.getMimeDecoder().decode(parameters.getFirstValue(name));
    } catch (IllegalArgumentException e) {
        throw new InvalidSamlRequestException(
                "failed to decode a base64 string of the parameter: " + name, e);
    }

    @SuppressWarnings("unchecked")
    final T message = (T) deserialize(decoded);

    final MessageContext<T> messageContext = new MessageContext<>();
    messageContext.setMessage(message);

    final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
    if (relayState != null) {
        final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
        assert context != null;
        context.setRelayState(relayState);
    }

    return messageContext;
}
 
Example 3
/**
 * Create a new SAML object.
 *
 * @param <T> the generic type
 * @param objectType the object type
 * @return the t
 */
public final <T extends SAMLObject> T newSamlObject(final Class<T> objectType) {
    final QName qName = getSamlObjectQName(objectType);
    final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>)
            XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName);
    if (builder == null) {
        throw new IllegalStateException("No SAMLObjectBuilder registered for class " + objectType.getName());
    }
    return objectType.cast(builder.buildObject(qName));
}
 
Example 4
Source Project: springboot-shiro-cas-mybatis   Source File: Saml10ObjectBuilder.java    License: MIT License 5 votes vote down vote up
/**
 * Encode response and pass it onto the outbound transport.
 * Uses {@link CasHTTPSOAP11Encoder} to handle encoding.
 *
 * @param httpResponse the http response
 * @param httpRequest the http request
 * @param samlMessage the saml response
 * @throws Exception the exception in case encoding fails.
 */
public void encodeSamlResponse(final HttpServletResponse httpResponse,
                               final HttpServletRequest httpRequest,
                               final Response samlMessage) throws Exception {

    final HTTPSOAP11Encoder encoder = new CasHTTPSOAP11Encoder();
    final MessageContext<SAMLObject> context = new MessageContext();
    context.setMessage(samlMessage);
    encoder.setHttpServletResponse(httpResponse);
    encoder.setMessageContext(context);
    encoder.initialize();
    encoder.prepareContext();
    encoder.encode();
}
 
Example 5
Source Project: saml-client   Source File: SamlClient.java    License: MIT License 5 votes vote down vote up
private SAMLObject parseResponse(String encodedResponse, String method) throws SamlException {
  logger.trace("Validating SAML response " + encodedResponse);
  try {
    Document responseDocument = domParser.parse(decodeAndInflate(encodedResponse, method));
    return (SAMLObject)
        XMLObjectProviderRegistrySupport.getUnmarshallerFactory()
            .getUnmarshaller(responseDocument.getDocumentElement())
            .unmarshall(responseDocument.getDocumentElement());
  } catch (UnmarshallingException | XMLParserException ex) {
    throw new SamlException("Cannot decode xml encoded response", ex);
  }
}
 
Example 6
Source Project: armeria   Source File: HttpRedirectBindingUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a redirected URL which includes a deflated base64 string that is converted from the specified
 * {@link SAMLObject}. The URL must contain a signature of the generated query string.
 */
static String toRedirectionUrl(SAMLObject msg,
                               String endpointUrl,
                               String messageParamName,
                               Credential signingCredential,
                               String signatureAlgorithm,
                               @Nullable String relayState) {
    requireNonNull(msg, "msg");
    requireNonNull(endpointUrl, "endpointUrl");
    requireNonNull(messageParamName, "messageParamName");
    requireNonNull(signingCredential, "signingCredential");
    requireNonNull(signatureAlgorithm, "signatureAlgorithm");

    final QueryParamsBuilder params = QueryParams.builder();
    params.add(messageParamName, toDeflatedBase64(msg));

    if (relayState != null) {
        // RelayState data MAY be included with a SAML protocol message transmitted with this binding.
        // The value MUST NOT exceed 80 bytes in length and SHOULD be integrity protected by the entity
        // creating the message independent of any other protections that may or may not exist
        // during message transmission.
        if (relayState.length() > 80) {
            throw new IllegalArgumentException("too long relayState string: " + relayState.length());
        }
        params.add(RELAY_STATE, relayState);
    }

    params.add(SIGNATURE_ALGORITHM, signatureAlgorithm);

    // Use URL-encoded query string as input.
    final String input = params.toQueryString();
    final String output = generateSignature(signingCredential, signatureAlgorithm, input);
    params.add(SIGNATURE, output);

    return endpointUrl + '?' + params.toQueryString();
}
 
Example 7
Source Project: armeria   Source File: SamlServiceProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
private AggregatedHttpResponse sendViaHttpRedirectBindingProtocol(
        String path, String paramName, SAMLObject samlObject) throws Exception {

    final QueryParamsBuilder params = QueryParams.builder();
    params.add(paramName, toDeflatedBase64(samlObject));
    params.add(SIGNATURE_ALGORITHM, signatureAlgorithm);
    final String input = params.toQueryString();
    final String output = generateSignature(idpCredential, signatureAlgorithm, input);
    params.add(SIGNATURE, output);

    final HttpRequest req = HttpRequest.of(HttpMethod.POST, path, MediaType.FORM_DATA,
                                           params.toQueryString());
    return client.execute(req).aggregate().join();
}
 
Example 8
@SuppressWarnings("unchecked")
public void handleSloGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof LogoutRequest)) {
            throw new RuntimeException("Expected LogoutRequest; received: " + messageContext.getMessage());
        }

        LogoutRequest logoutRequest = (LogoutRequest) messageContext.getMessage();

        SAML2HTTPRedirectDeflateSignatureSecurityHandler signatureSecurityHandler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
        SignatureValidationParameters validationParams = new SignatureValidationParameters();
        SecurityParametersContext securityParametersContext = messageContext
                .getSubcontext(SecurityParametersContext.class, true);

        SAMLPeerEntityContext peerEntityContext = messageContext.getSubcontext(SAMLPeerEntityContext.class, true);
        peerEntityContext.setEntityId(idpEntityId);
        peerEntityContext.setRole(org.opensaml.saml.saml2.metadata.SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        SAMLProtocolContext protocolContext = messageContext.getSubcontext(SAMLProtocolContext.class, true);
        protocolContext.setProtocol(SAMLConstants.SAML20P_NS);

        validationParams.setSignatureTrustEngine(buildSignatureTrustEngine(this.spSignatureCertificate));
        securityParametersContext.setSignatureValidationParameters(validationParams);
        signatureSecurityHandler.setHttpServletRequest(httpServletRequest);
        signatureSecurityHandler.initialize();
        signatureSecurityHandler.invoke(messageContext);

        if (!this.authenticateUser.equals(logoutRequest.getNameID().getValue())) {
            throw new RuntimeException("Unexpected NameID in LogoutRequest: " + logoutRequest);
        }

    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException
            | MessageHandlerException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source Project: armeria   Source File: HttpRedirectBindingUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Converts an {@link AggregatedHttpRequest} which is received from the remote entity to
 * a {@link SAMLObject}.
 */
@SuppressWarnings("unchecked")
static <T extends SAMLObject> MessageContext<T> toSamlObject(
        AggregatedHttpRequest req, String name,
        Map<String, SamlIdentityProviderConfig> idpConfigs,
        @Nullable SamlIdentityProviderConfig defaultIdpConfig) {
    requireNonNull(req, "req");
    requireNonNull(name, "name");
    requireNonNull(idpConfigs, "idpConfigs");

    final SamlParameters parameters = new SamlParameters(req);
    final T message = (T) fromDeflatedBase64(parameters.getFirstValue(name));

    final MessageContext<T> messageContext = new MessageContext<>();
    messageContext.setMessage(message);

    final Issuer issuer;
    if (message instanceof RequestAbstractType) {
        issuer = ((RequestAbstractType) message).getIssuer();
    } else if (message instanceof StatusResponseType) {
        issuer = ((StatusResponseType) message).getIssuer();
    } else {
        throw new InvalidSamlRequestException(
                "invalid message type: " + message.getClass().getSimpleName());
    }

    // Use the default identity provider config if there's no issuer.
    final SamlIdentityProviderConfig config;
    if (issuer != null) {
        final String idpEntityId = issuer.getValue();
        config = idpConfigs.get(idpEntityId);
        if (config == null) {
            throw new InvalidSamlRequestException(
                    "a message from unknown identity provider: " + idpEntityId);
        }
    } else {
        if (defaultIdpConfig == null) {
            throw new InvalidSamlRequestException("failed to get an Issuer element");
        }
        config = defaultIdpConfig;
    }

    // If this message is sent via HTTP-redirect binding protocol, its signature parameter should
    // be validated.
    validateSignature(config.signingCredential(), parameters, name);

    final String relayState = parameters.getFirstValueOrNull(RELAY_STATE);
    if (relayState != null) {
        final SAMLBindingContext context = messageContext.getSubcontext(SAMLBindingContext.class, true);
        assert context != null;
        context.setRelayState(relayState);
    }

    return messageContext;
}
 
Example 10
Source Project: armeria   Source File: SamlMessageUtil.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
static <T extends SAMLObject> SAMLObjectBuilder<T> builder(@Nullable final QName key) {
    final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>) builderFactory.getBuilder(key);
    assert builder != null;
    return builder;
}
 
Example 11
Source Project: armeria   Source File: SamlMessageUtil.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
static <T extends SAMLObject> T build(@Nullable final QName key) {
    return (T) builder(key).buildObject();
}
 
Example 12
/**
 * Build the saml object based on its QName.
 *
 * @param objectType the object
 * @param qName the QName
 * @param <T> the object type
 * @return the saml object
 */
private <T extends SAMLObject> T newSamlObject(final Class<T> objectType, final QName qName) {
    final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName);
    if (builder == null) {
        throw new IllegalStateException("No SAMLObjectBuilder registered for class " + objectType.getName());
    }
    return objectType.cast(builder.buildObject());
}