Java Code Examples for org.opensaml.messaging.context.MessageContext#getMessage()

The following examples show how to use org.opensaml.messaging.context.MessageContext#getMessage() . 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: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
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 File: SamlAssertionConsumerFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, AggregatedHttpRequest req,
                          String defaultHostname, SamlPortConfig portConfig) {
    try {
        final MessageContext<Response> messageContext;
        if (cfg.endpoint().bindingProtocol() == SamlBindingProtocol.HTTP_REDIRECT) {
            messageContext = HttpRedirectBindingUtil.toSamlObject(req, SAML_RESPONSE,
                                                                  idpConfigs, defaultIdpConfig);
        } else {
            messageContext = HttpPostBindingUtil.toSamlObject(req, SAML_RESPONSE);
        }

        final String endpointUri = cfg.endpoint().toUriString(portConfig.scheme().uriText(),
                                                              defaultHostname, portConfig.port());
        final Response response = messageContext.getMessage();
        final Assertion assertion = getValidatedAssertion(response, endpointUri);

        // Find a session index which is sent by an identity provider.
        final String sessionIndex = assertion.getAuthnStatements().stream()
                                             .map(AuthnStatement::getSessionIndex)
                                             .filter(Objects::nonNull)
                                             .findFirst().orElse(null);

        final SAMLBindingContext bindingContext = messageContext.getSubcontext(SAMLBindingContext.class);
        final String relayState = bindingContext != null ? bindingContext.getRelayState() : null;

        return ssoHandler.loginSucceeded(ctx, req, messageContext, sessionIndex, relayState);
    } catch (SamlException e) {
        return ssoHandler.loginFailed(ctx, req, null, e);
    }
}
 
Example 3
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@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 4
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
/**
     * Extracts session based credentials from the request. Returns
     * <code>null</code> if the secure user data is not present either in the HTTP Session.
     */
    @Override
    public AuthenticationInfo extractCredentials(final HttpServletRequest httpServletRequest,
                                                 final HttpServletResponse httpServletResponse)  {
// 1. If the request is POST to the ACS URL, it needs to extract the Auth Info from the SAML data POST'ed
        if (saml2ConfigService.getSaml2SPEnabled() ) {
            String reqURI = httpServletRequest.getRequestURI();
            if (reqURI.equals(saml2ConfigService.getAcsPath())){
                doClassloading();
                MessageContext messageContext = decodeHttpPostSamlResp(httpServletRequest);
                boolean relayStateIsOk = validateRelayState(httpServletRequest, messageContext);
                // If relay state from request = relay state from session))
                if (relayStateIsOk) {
                    Response response = (Response) messageContext.getMessage();
                    EncryptedAssertion encryptedAssertion = response.getEncryptedAssertions().get(0);
                    Assertion assertion = decryptAssertion(encryptedAssertion);
                    verifyAssertionSignature(assertion);
                    if (validateSaml2Conditions(httpServletRequest, assertion)){
                        logger.debug("Decrypted Assertion: ");
                        Helpers.logSAMLObject(assertion);
                        User extUser = doUserManagement(assertion);
                        AuthenticationInfo newAuthInfo = this.buildAuthInfo(extUser);
                        return newAuthInfo;
                    }
                    logger.error("Validation of SubjectConfirmation failed");
                }
                return null;
// 2.  try credentials from the session
            } else {
                // Request context is not the ACS path, so get the authInfo from session.
                String authData = authStorage.getString(httpServletRequest);
                if (authData != null) {
                    if (tokenStore.isValid(authData)) {
                        return buildAuthInfo(authData);
                    } else {
                        // clear the token from the session, its invalid and we should get rid of it
                        // so that the invalid cookie isn't present on the authN operation.
                        authStorage.clear(httpServletRequest, httpServletResponse);
                        if ( AuthUtil.isValidateRequest(httpServletRequest)) {
                            // signal the requestCredentials method a previous login failure
                            httpServletRequest.setAttribute(FAILURE_REASON, SamlReason.TIMEOUT);
                            return AuthenticationInfo.FAIL_AUTH;
                        }
                    }
                }
            }
        }
        return null;
    }