Java Code Examples for org.opensaml.saml2.core.Response

The following examples show how to use org.opensaml.saml2.core.Response. 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
Source Project: carbon-identity   Source File: DefaultResponseBuilder.java    License: 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 2
Source Project: MaxKey   Source File: ConsumerEndpoint.java    License: 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 3
Source Project: MaxKey   Source File: ConsumerEndpoint.java    License: 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 Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 6 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 5
Source Project: carbon-identity   Source File: ErrorResponseBuilder.java    License: 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 6
Source Project: carbon-identity   Source File: ErrorResponseBuilder.java    License: 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 7
Source Project: carbon-identity   Source File: LoggedInSessionBean.java    License: 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 8
Source Project: secure-data-service   Source File: SamlHelper.java    License: 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 9
Source Project: secure-data-service   Source File: SamlHelperTest.java    License: 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 Project: lams   Source File: BaseSAML2MessageDecoder.java    License: 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);
}
 
Example 11
Source Project: lams   Source File: ResponseUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    Response resp = (Response) parentSAMLObject;

    if (childSAMLObject instanceof Assertion) {
        resp.getAssertions().add((Assertion) childSAMLObject);
    } else if (childSAMLObject instanceof EncryptedAssertion) {
        resp.getEncryptedAssertions().add((EncryptedAssertion) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example 12
Source Project: MaxKey   Source File: AssertionEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/authz/saml20/assertion")
public ModelAndView assertion(HttpServletRequest request,HttpServletResponse response) throws Exception {
	logger.debug("saml20 assertion start.");
	bindingAdapter = (BindingAdapter) request.getSession().getAttribute("samlv20Adapter");
	logger.debug("saml20 assertion get session samlv20Adapter "+bindingAdapter);
	AppsSAML20Details saml20Details = bindingAdapter.getSaml20Details();
	logger.debug("saml20Details "+saml20Details.getExtendAttr());
	AuthnRequestInfo authnRequestInfo = bindingAdapter.getAuthnRequestInfo();
	
	if (authnRequestInfo == null) {
		logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
		throw new Exception();
	}

	logger.debug("AuthnRequestInfo: {}", authnRequestInfo);

	HashMap <String,String>attributeMap=new HashMap<String,String>();
	//saml20Details
	Response authResponse = authnResponseGenerator.generateAuthnResponse(
			saml20Details,
			authnRequestInfo,
			attributeMap,
			bindingAdapter);
	
	Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl());

	request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

	// we could use a different adapter to send the response based on
	// request issuer...
	try {
		bindingAdapter.sendSAMLMessage(authResponse, endpoint, request,response);
	} catch (MessageEncodingException mee) {
		logger.error("Exception encoding SAML message", mee);
		throw new Exception(mee);
	}
	return null;
}
 
Example 13
Source Project: carbon-identity   Source File: SAML2SSOUIAuthenticator.java    License: 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 14
Source Project: carbon-identity   Source File: SAML2SSOUIAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return username username contained in the SAML Response
 */
private String getUsernameFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the first one
        assertion = assertions.get(0);
        return assertion.getSubject().getNameID().getValue();
    }
    return null;
}
 
Example 15
Source Project: carbon-identity   Source File: SAML2SSOUIAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read the session index from a Response
 *
 * @param response SAML Response
 * @return Session Index value contained in the Response
 */
private String getSessionIndexFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    String sessionIndex = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the first one
        List<AuthnStatement> authnStatements = assertions.get(0).getAuthnStatements();
        if (authnStatements != null && authnStatements.size() > 0) {
            // There can be only one authentication stmt inside the SAML assertion of a SAML Response
            AuthnStatement authStmt = authnStatements.get(0);
            sessionIndex = authStmt.getSessionIndex();
        }
    }
    return sessionIndex;
}
 
Example 16
Source Project: carbon-identity   Source File: Util.java    License: 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 17
Source Project: carbon-identity   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return username username contained in the SAML Response
 */
public static String getUsernameFromResponse(Response response) {

    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        // There can be only one assertion in a SAML Response, so get the
        // first one
        assertion = assertions.get(0);
        return getUsernameFromAssertion(assertion);

    }
    return null;
}
 
Example 18
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Validate the signature of a SAML2 XMLObject
 *
 * @param xmlObject  SAML2 XMLObject
 * @param domainName domain name of the subject
 * @return true, if signature is valid.
 */
private boolean validateSignature(XMLObject xmlObject, String domainName) {
    if (xmlObject instanceof Response) {
        return validateSignature((Response) xmlObject, domainName);
    } else if (xmlObject instanceof Assertion) {
        return validateSignature((Assertion) xmlObject, domainName);
    } else {
        log.error("Only Response and Assertion objects are validated in this authendicator");
        return false;
    }
}
 
Example 19
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: 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 20
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: 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 21
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get roles from the SAML2 XMLObject
 *
 * @param xmlObject SAML2 XMLObject
 * @return String array of roles
 */
private String[] getRoles(XMLObject xmlObject) {
    String[] arrRoles = {};
    if (xmlObject instanceof Response) {
        return getRolesFromResponse((Response) xmlObject);
    } else if (xmlObject instanceof Assertion) {
        return getRolesFromAssertion((Assertion) xmlObject);
    } else {
        return arrRoles;
    }
}
 
Example 22
Source Project: carbon-identity   Source File: SAML2SSOAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get roles from the SAML2 Response
 *
 * @param response SAML2 Response
 * @return roles array
 */
private String[] getRolesFromResponse(Response response) {
    List<Assertion> assertions = response.getAssertions();
    Assertion assertion = null;
    if (assertions != null && assertions.size() > 0) {
        assertion = assertions.get(0);
        return getRolesFromAssertion(assertion);
    }
    return null;
}
 
Example 23
/**
 * @param id
 * @param status
 * @param statMsg
 * @return
 * @throws Exception
 */
private SAMLSSORespDTO buildErrorResponse(String id, String status,
                                          String statMsg, String destination) throws Exception {
    SAMLSSORespDTO samlSSORespDTO = new SAMLSSORespDTO();
    ErrorResponseBuilder errRespBuilder = new ErrorResponseBuilder();
    List<String> statusCodeList = new ArrayList<String>();
    statusCodeList.add(status);
    Response resp = errRespBuilder.buildResponse(id, statusCodeList, statMsg, destination);
    String encodedResponse = SAMLSSOUtil.compressResponse(SAMLSSOUtil.marshall(resp));

    samlSSORespDTO.setRespString(encodedResponse);
    samlSSORespDTO.setSessionEstablished(false);
    return samlSSORespDTO;
}
 
Example 24
/**
 * @param id
 * @param status
 * @param statMsg
 * @return
 * @throws Exception
 */
private SAMLSSORespDTO buildErrorResponse(String id, String status,
                                          String statMsg, String destination) throws Exception {
    SAMLSSORespDTO samlSSORespDTO = new SAMLSSORespDTO();
    ErrorResponseBuilder errRespBuilder = new ErrorResponseBuilder();
    List<String> statusCodeList = new ArrayList<String>();
    statusCodeList.add(status);
    Response resp = errRespBuilder.buildResponse(id, statusCodeList, statMsg, destination);
    String encodedResp = SAMLSSOUtil.compressResponse(SAMLSSOUtil.marshall(resp));
    samlSSORespDTO.setRespString(encodedResp);
    samlSSORespDTO.setSessionEstablished(false);
    return samlSSORespDTO;
}
 
Example 25
Source Project: carbon-identity   Source File: SAMLSSOUtil.java    License: 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 26
Source Project: carbon-identity   Source File: SAMLResponseBuilder.java    License: 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 27
Source Project: carbon-identity   Source File: SAML2SSOManager.java    License: 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 28
Source Project: saml-sdk-java   Source File: SAMLClient.java    License: 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 29
Source Project: carbon-commons   Source File: Util.java    License: 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 30
Source Project: carbon-commons   Source File: SAMLSSORelyingPartyObject.java    License: 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;
}