org.opensaml.saml2.core.Response Java Examples

The following examples show how to use org.opensaml.saml2.core.Response. 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: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 8 votes vote down vote up
/**
 * Get the Assertion from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return assertion
 */
private Assertion getAssertionFromResponse(Response response) {
    Assertion assertion = null;
    if (response != null) {
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            assertion = assertions.get(0);
        } else {
            log.error("SAML2 Response doesn't contain Assertions");
        }
    }
    return assertion;
}
 
Example #2
Source File: DefaultResponseBuilder.java    From carbon-identity with Apache License 2.0 7 votes vote down vote up
public Response buildResponse(SAMLSSOAuthnReqDTO authReqDTO, Assertion assertion)
        throws IdentityException {

    if (log.isDebugEnabled()) {
        log.debug("Building SAML Response for the consumer '"
                + authReqDTO.getAssertionConsumerURL() + "'");
    }
    Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject();
    response.setIssuer(SAMLSSOUtil.getIssuer());
    response.setID(SAMLSSOUtil.createID());
    response.setInResponseTo(authReqDTO.getId());
    response.setDestination(authReqDTO.getAssertionConsumerURL());
    response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null));
    response.setVersion(SAMLVersion.VERSION_20);
    DateTime issueInstant = new DateTime();
    response.setIssueInstant(issueInstant);
    response.getAssertions().add(assertion);
    if (authReqDTO.isDoSignResponse()) {
        SAMLSSOUtil.setSignature(response, authReqDTO.getSigningAlgorithmUri(), authReqDTO.getDigestAlgorithmUri
                (), new SignKeyDataHolder(authReqDTO.getUser().getAuthenticatedSubjectIdentifier()));
    }
    return response;
}
 
Example #3
Source File: ConsumerEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
private StringBuilder extractExtraInformation(Response samlResponse) {
	StringBuilder extraInformation = new StringBuilder();
	
	if( samlResponse.getStatus().getStatusCode().getStatusCode() !=null ) {
	
		extraInformation.append(samlResponse.getStatus().getStatusCode().getStatusCode().getValue());
	}
	
	if(samlResponse.getStatus().getStatusMessage() != null) {
		if(extraInformation.length() > 0) {
			extraInformation.append("  -  ");
		}
		extraInformation.append(samlResponse.getStatus().getStatusMessage());
	}
	return extraInformation;
}
 
Example #4
Source File: LoggedInSessionBean.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException, SSOAgentException {

    subjectId = (String) stream.readObject();

    responseString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(responseString)) {
        response = (Response) SSOAgentUtils.unmarshall(responseString);
    }

    assertionString = (String) stream.readObject();
    if (responseString != null && !EMPTY_STRING.equals(assertionString)) {
        assertion = (Assertion) SSOAgentUtils.unmarshall(assertionString);
    }

    sessionIndex = (String) stream.readObject();
    String accessTokenResponseBeanString = (String) stream.readObject();
    if (!EMPTY_STRING.equals(accessTokenResponseBeanString)) {
        accessTokenResponseBean = accessTokenResponseBean.deSerialize(accessTokenResponseBeanString);
    } else {
        accessTokenResponseBean = null;
    }
    subjectAttributes = (Map) stream.readObject();
}
 
Example #5
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public static String generateErrorneousResponse() {
    Response response = new ResponseBuilder().buildObject();
    response.setIssuer(getIssuer());
    response.setStatus(buildStatus());
    response.setVersion(SAMLVersion.VERSION_20);
    response.setID(UIDGenerator.generateUID());

    try {
        return encode(marshall(response));
    } catch (IdentityException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while encoding.", e);
        }
        return null;
    }
}
 
Example #6
Source File: ErrorResponseBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Build the error response
 *
 * @param inResponseToID
 * @param statusCodes
 * @param statusMsg
 * @return
 */
public Response buildResponse(String inResponseToID, List<String> statusCodes, String statusMsg,
                              String destination) throws IdentityException {
    if (statusCodes == null || statusCodes.isEmpty()) {
        throw IdentityException.error("No Status Values");
    }
    response.setIssuer(SAMLSSOUtil.getIssuer());
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = null;
    for (String statCode : statusCodes) {
        statusCode = buildStatusCode(statCode, statusCode);
    }
    status.setStatusCode(statusCode);
    buildStatusMsg(status, statusMsg);
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);
    response.setID(SAMLSSOUtil.createID());
    if (inResponseToID != null) {
        response.setInResponseTo(inResponseToID);
    }
    if (destination != null) {
        response.setDestination(destination);
    }
    response.setIssueInstant(new DateTime());
    return response;
}
 
Example #7
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that the certificate in the saml assertion is valid and trusted.
 * @param samlResponse
 *      SAML response form the IdP.
 * @param assertion
 *      SAML assertion
 */
public void validateSignature(Response samlResponse, Assertion assertion)  {
    if(samlResponse.getSignature() == null && assertion.getSignature() == null) {
        raiseSamlValidationError("Invalid SAML message: Response is not signed", null);
    }

    String issuer = samlResponse.getIssuer().getValue();

    if(samlResponse.getSignature() != null) {
        validateFormatAndCertificate(samlResponse.getSignature(), samlResponse.getDOM(), issuer);
    }

    if(assertion.getSignature() != null) {
        validateFormatAndCertificate(assertion.getSignature(), assertion.getDOM(), issuer);
    }
}
 
Example #8
Source File: ConsumerEndpoint.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
private void additionalValidationChecksOnSuccessfulResponse(
		Response samlResponse) {
	//saml validator suite does not check for assertions on successful auths
	if(samlResponse.getAssertions().isEmpty()){
		throw new ServiceProviderAuthenticationException("Successful Response did not contain any assertions");
	}
	
	//nor authnStatements
	else if(samlResponse.getAssertions().get(0).getAuthnStatements().isEmpty()){
		throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AuthnStatement");
	}

	//we require at attribute statements
	else if(samlResponse.getAssertions().get(0).getAttributeStatements().isEmpty()){
		throw new ServiceProviderAuthenticationException("Successful Response did not contain an assertions with an AttributeStatements");

	}
	//we will require an issuer
	else if(samlResponse.getIssuer() == null) {
		throw new ServiceProviderAuthenticationException("Successful Response did not contain any Issuer");

	}
}
 
Example #9
Source File: SamlHelperTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsAssertionEncrypted() {
    Response samlResponse = Mockito.mock(Response.class);
    Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(null);

    boolean result = samlHelper.isAssertionEncrypted(samlResponse);
    Assert.assertFalse(result);

    Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(new ArrayList<EncryptedAssertion>());
    result = samlHelper.isAssertionEncrypted(samlResponse);
    Assert.assertFalse(result);

    EncryptedAssertion encryptedAssertion = Mockito.mock(EncryptedAssertion.class);
    List<EncryptedAssertion> assertionList = new ArrayList<EncryptedAssertion>();
    assertionList.add(encryptedAssertion);

    Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(assertionList);
    result = samlHelper.isAssertionEncrypted(samlResponse);
    Assert.assertTrue(result);
}
 
Example #10
Source File: SAMLSSORelyingPartyObject.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @param cx
 * @param thisObj
 * @param args    -args[0]- SAML response xml
 * @param funObj
 * @return
 * @throws Exception
 */
public static boolean jsFunction_validateSignature(Context cx, Scriptable thisObj,
                                                   Object[] args,
                                                   Function funObj)
        throws Exception {

    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. SAML response is missing.");
    }

    String decodedString = Util.decode((String) args[0]);

    XMLObject samlObject = Util.unmarshall(decodedString);
    String tenantDomain = Util.getDomainName(samlObject);

    int tenantId = Util.getRealmService().getTenantManager().getTenantId(tenantDomain);

    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;
        SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
        return Util.validateSignature(samlResponse,
                                      relyingPartyObject.getSSOProperty(SSOConstants.KEY_STORE_NAME),
                                      relyingPartyObject.getSSOProperty(SSOConstants.KEY_STORE_PASSWORD),
                                      relyingPartyObject.getSSOProperty(SSOConstants.IDP_ALIAS),
                                      tenantId, tenantDomain);
    }
    if (log.isWarnEnabled()) {
        log.warn("SAML response in signature validation is not a SAML Response.");
    }
    return false;
}
 
Example #11
Source File: SAMLSSOUtil.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * build the error response
 *
 * @param status
 * @param message
 * @return decoded response
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static String buildErrorResponse(String status, String message, String destination)
        throws IdentityException, IOException {

    ErrorResponseBuilder respBuilder = new ErrorResponseBuilder();
    List<String> statusCodeList = new ArrayList<String>();
    statusCodeList.add(status);
    Response response = respBuilder.buildResponse(null, statusCodeList, message, destination);
    String resp = SAMLSSOUtil.marshall(response);
    return compressResponse(resp);
}
 
Example #12
Source File: SAML2SSOUIAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
public boolean canHandle(HttpServletRequest request) {
    String relayState = request.getParameter(SAML2SSOAuthenticatorConstants.HTTP_POST_PARAM_RELAY_STATE);
    Object samlResponse = request.getAttribute(SAML2SSOAuthenticatorConstants.HTTP_ATTR_SAML2_RESP_TOKEN);
    // if it is a logout request, do not check for Response and Relay State
    if (request.getRequestURI().indexOf("/carbon/admin/logout_action.jsp") > -1) {
        return true;
    }
    // in case of a login request, check for Response and Relay State
    if (samlResponse != null && samlResponse instanceof Response && relayState != null) {
        return true;
    }
    return false;
}
 
Example #13
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the signature of a SAML2 Response
 *
 * @param response   SAML2 Response
 * @param domainName domain name of the subject
 * @return true, if signature is valid.
 */
private boolean validateSignature(Response response, String domainName) {
    boolean isSignatureValid = false;
    if (response.getSignature() == null) {
        log.error("SAML Response is not signed. So authentication process will be terminated.");
    } else {
        isSignatureValid = validateSignature(response.getSignature(), domainName);
    }
    return isSignatureValid;
}
 
Example #14
Source File: SAMLResponseBuilder.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Build SAML response using IdP configuration & user name
 *
 * @param ssoIdPConfigs
 * @param userName
 * @return SAML Response object
 * @throws IdentityException
 */
public Response buildSAMLResponse(SAMLSSOServiceProviderDO ssoIdPConfigs, String userName)
        throws IdentityException {
    if (log.isDebugEnabled()) {
        log.debug("Building SAML Response for the consumer '" +
                ssoIdPConfigs.getAssertionConsumerUrl() + "'");
    }
    Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject();
    response.setIssuer(SAMLSSOUtil.getIssuer());
    response.setID(SAMLSSOUtil.createID());
    response.setDestination(ssoIdPConfigs.getAssertionConsumerUrl());
    response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null));
    response.setVersion(SAMLVersion.VERSION_20);
    DateTime issueInstant = new DateTime();
    DateTime notOnOrAfter =
            new DateTime(issueInstant.getMillis() +
                    SAMLSSOUtil.getSAMLResponseValidityPeriod() * 60 *
                            1000);
    response.setIssueInstant(issueInstant);
    Assertion assertion = buildSAMLAssertion(ssoIdPConfigs, notOnOrAfter, userName);
    if (ssoIdPConfigs.isDoEnableEncryptedAssertion()) {
        String domainName = MultitenantUtils.getTenantDomain(userName);
        String alias = ssoIdPConfigs.getCertAlias();
        if (alias != null) {
            EncryptedAssertion encryptedAssertion =
                    SAMLSSOUtil.setEncryptedAssertion(assertion,
                            EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256,
                            alias,
                            domainName);
            response.getEncryptedAssertions().add(encryptedAssertion);
        }
    } else {
        response.getAssertions().add(assertion);
    }
    if (ssoIdPConfigs.isDoSignResponse()) {
        SAMLSSOUtil.setSignature(response, ssoIdPConfigs.getSigningAlgorithmUri(), ssoIdPConfigs
                .getDigestAlgorithmUri(), new SignKeyDataHolder(userName));
    }
    return response;
}
 
Example #15
Source File: Util.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 XMLObject
 *
 * @param xmlObject SAML2 XMLObject
 * @return username
 */
public static String getUsername(XMLObject xmlObject) {

    if (xmlObject instanceof Response) {
        return getUsernameFromResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return getUsernameFromAssertion((Assertion) xmlObject);
    } else {
        return null;
    }
}
 
Example #16
Source File: SAML2SSOManager.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
protected boolean isNoPassive(Response response) {

        return response.getStatus() != null &&
                response.getStatus().getStatusCode() != null &&
                response.getStatus().getStatusCode().getValue().equals(StatusCode.RESPONDER_URI) &&
                response.getStatus().getStatusCode().getStatusCode() != null &&
                response.getStatus().getStatusCode().getStatusCode().getValue().equals(
                        StatusCode.NO_PASSIVE_URI);
    }
 
Example #17
Source File: SAML2SSOAuthenticator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the AudienceRestriction of SAML2 XMLObject
 *
 * @param xmlObject Unmarshalled SAML2 Response
 * @return validity
 */
private boolean validateAudienceRestrictionInXML(XMLObject xmlObject) {
    if (xmlObject instanceof Response) {
        return validateAudienceRestrictionInResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return validateAudienceRestrictionInAssertion((Assertion) xmlObject);
    } else {
        log.error("Only Response and Assertion objects are validated in this authendicator");
        return false;
    }
}
 
Example #18
Source File: SAMLClient.java    From saml-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all supplied assertions, decrypting any encrypted
 * assertions if necessary.
 */
private List<Assertion> getAssertions(Response response)
    throws DecryptionException
{
    List<Assertion> assertions = new ArrayList<Assertion>();
    assertions.addAll(response.getAssertions());

    for (EncryptedAssertion e : response.getEncryptedAssertions()) {
        assertions.add(decrypt(e));
    }

    return assertions;
}
 
Example #19
Source File: Util.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * This method validates the signature of the SAML Response.
 * @param resp SAML Response
 * @return true, if signature is valid.
 */
public static boolean validateSignature(Response resp, String keyStoreName,
                                        String keyStorePassword, String alias, int tenantId,
                                        String tenantDomain) {
    boolean isSigValid = false;
    try {
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        if(log.isDebugEnabled()){
            log.debug("Validating against "+cert.getSubjectDN().getName());
        }
        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(resp.getSignature());
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        if (log.isDebugEnabled()){
        log.debug("Signature verification is failed for "+tenantDomain);
        }
        return isSigValid;
    }
}
 
Example #20
Source File: SamlHelperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test (expected = APIAccessDeniedException.class)
public void testNonSamlResponseXml() {
    String postData = "<saml2:AttributeService xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:metadata\"></saml2:AttributeService>";
    Document doc = samlHelper.parseToDoc(postData);

    Response samlResponse = samlHelper.convertToSAMLResponse(doc.getDocumentElement());

    Assert.assertNull(samlResponse);
}
 
Example #21
Source File: SAMLSSORelyingPartyObject.java    From carbon-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the name of authenticated user from SAML response.
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws Exception
 */
public static String jsFunction_getSAMLResponseNameId(Context cx, Scriptable thisObj,
                                                      Object[] args,
                                                      Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. The SAML response is missing.");
    }
    String decodedString = Util.decode((String) args[0]);
    XMLObject samlObject = Util.unmarshall(decodedString);
    String username = null;

    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;
        List<Assertion> assertions = samlResponse.getAssertions();

        // extract the username
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
    }
    if (username == null) {
        throw new Exception("Failed to get subject assertion from SAML response.");
    }
    return username;
}
 
Example #22
Source File: SamlAssertionProducer.java    From saml-generator with Apache License 2.0 5 votes vote down vote up
private Response createResponse(final DateTime issueDate, Issuer issuer, Status status, Assertion assertion) {
	ResponseBuilder responseBuilder = new ResponseBuilder();
	Response response = responseBuilder.buildObject();
	response.setID(UUID.randomUUID().toString());
	response.setIssueInstant(issueDate);
	response.setVersion(SAMLVersion.VERSION_20);
	response.setIssuer(issuer);
	response.setStatus(status);
	response.getAssertions().add(assertion);
	return response;
}
 
Example #23
Source File: SAML2LoginAPIAuthenticatorCmd.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public Response processSAMLResponse(String responseMessage) {
    Response responseObject = null;
    try {
        DefaultBootstrap.bootstrap();
        responseObject = SAMLUtils.decodeSAMLResponse(responseMessage);

    } catch (ConfigurationException | FactoryConfigurationError | ParserConfigurationException | SAXException | IOException | UnmarshallingException e) {
        s_logger.error("SAMLResponse processing error: " + e.getMessage());
    }
    return responseObject;
}
 
Example #24
Source File: SAMLUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public static Response decodeSAMLResponse(String responseMessage)
        throws ConfigurationException, ParserConfigurationException,
        SAXException, IOException, UnmarshallingException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    byte[] base64DecodedResponse = Base64.decode(responseMessage);
    Document document = docBuilder.parse(new ByteArrayInputStream(base64DecodedResponse));
    Element element = document.getDocumentElement();
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
    return (Response) unmarshaller.unmarshall(element);
}
 
Example #25
Source File: SAML2LoginAPIAuthenticatorCmdTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private Response buildMockResponse() throws Exception {
    Response samlMessage = new ResponseBuilder().buildObject();
    samlMessage.setID("foo");
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("MockedIssuer");
    samlMessage.setIssuer(issuer);
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = new StatusCodeBuilder().buildObject();
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    samlMessage.setStatus(status);
    Assertion assertion = new AssertionBuilder().buildObject();
    Subject subject = new SubjectBuilder().buildObject();
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue("SOME-UNIQUE-ID");
    nameID.setFormat(NameIDType.PERSISTENT);
    subject.setNameID(nameID);
    assertion.setSubject(subject);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setSessionIndex("Some Session String");
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    assertion.getAttributeStatements().add(attributeStatement);
    samlMessage.getAssertions().add(assertion);
    return samlMessage;
}
 
Example #26
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Convert w3c element to a SAML response
 * @param element
 * @return
 */
public org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element) {
    org.opensaml.saml2.core.Response samlResponse = null;

    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

    if(unmarshaller == null) {
        raiseSamlValidationError("Invalid SAML Response", null);
    }

    XMLObject responseXmlObj = null;

    try {
        responseXmlObj = unmarshaller.unmarshall(element);
    } catch (UnmarshallingException e) {
        raiseSamlValidationError("Error unmarshalling response from IdP", null);
    }

    if (responseXmlObj instanceof org.opensaml.saml2.core.Response) {
        samlResponse = (org.opensaml.saml2.core.Response) responseXmlObj;
    } else {
        raiseSamlValidationError("Response is in an improper format", null);
    }

    return samlResponse;
}
 
Example #27
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry) {
    Assertion assertion;
    if (isAssertionEncrypted(samlResponse)) {
        assertion = decryptAssertion(samlResponse.getEncryptedAssertions().get(0), keystoreEntry);
    } else {
        assertion = samlResponse.getAssertions().get(0);
    }
    return assertion;
}
 
Example #28
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public void validateStatus(org.opensaml.saml2.core.Response samlResponse) {
    Status responseStatus = samlResponse.getStatus();
    StatusCode statusCode = responseStatus.getStatusCode();
    String statusValue = statusCode.getValue();

    if (!statusValue.equals(SUCCESS_STATUS)) {
        LOG.error("SAML Response did not have a success status, instead status was {}", statusValue);
    }
}
 
Example #29
Source File: SamlHelperTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Test (expected = APIAccessDeniedException.class)
public void testNonSamlXml() {
    String postData = "<test><child>text</child></test>";
    Document doc = samlHelper.parseToDoc(postData);

    Response samlResponse = samlHelper.convertToSAMLResponse(doc.getDocumentElement());
    Assert.assertNull(samlResponse);
}
 
Example #30
Source File: BaseSAML2MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract information from a SAML StatusResponse message.
 * 
 * @param messageContext current message context
 * @param statusResponse the SAML message to process
 * 
 * @throws MessageDecodingException thrown if the response issuer has a format other than {@link NameIDType#ENTITY}
 *             or, if the response does not contain an issuer, if the contained assertions contain issuers that are
 *             not of {@link NameIDType#ENTITY} format or if the assertions contain different issuers
 */
protected void extractResponseInfo(SAMLMessageContext messageContext, StatusResponseType statusResponse)
        throws MessageDecodingException {

    messageContext.setInboundSAMLMessageId(statusResponse.getID());
    messageContext.setInboundSAMLMessageIssueInstant(statusResponse.getIssueInstant());

    // If response doesn't have an issuer, look at the first
    // enclosed assertion
    String messageIssuer = null;
    if (statusResponse.getIssuer() != null) {
        messageIssuer = extractEntityId(statusResponse.getIssuer());
    } else if (statusResponse instanceof Response) {
        List<Assertion> assertions = ((Response) statusResponse).getAssertions();
        if (assertions != null && assertions.size() > 0) {
            log.info("Status response message had no issuer, attempting to extract issuer from enclosed Assertion(s)");
            String assertionIssuer;
            for (Assertion assertion : assertions) {
                if (assertion != null && assertion.getIssuer() != null) {
                    assertionIssuer = extractEntityId(assertion.getIssuer());
                    if (messageIssuer != null && !messageIssuer.equals(assertionIssuer)) {
                        throw new MessageDecodingException("SAML 2 assertions, within response "
                                + statusResponse.getID() + " contain different issuer IDs");
                    }
                    messageIssuer = assertionIssuer;
                }
            }
        }
    }

    messageContext.setInboundMessageIssuer(messageIssuer);
}