Search in sources :

Example 96 with Response

use of org.opensaml.saml2.core.Response in project verify-hub by alphagov.

the class ExecuteAttributeQueryRequestTest method run_shouldCallInboundMessageValidatorWithAttributeQuery.

@Test
public void run_shouldCallInboundMessageValidatorWithAttributeQuery() throws Exception {
    when(attributeQueryRequestClient.sendQuery(any(Element.class), anyString(), any(SessionId.class), any(URI.class))).thenReturn(matchingServiceResponse);
    Response response = aResponse().build();
    when(elementToResponseTransformer.apply(matchingServiceResponse)).thenReturn(response);
    executeAttributeQueryRequest.execute(sessionId, attributeQueryContainerDto);
    verify(matchingRequestSignatureValidator).validate(attributeQuery, HUB_ROLE);
}
Also used : Response(org.opensaml.saml.saml2.core.Response) ResponseBuilder.aResponse(uk.gov.ida.saml.core.test.builders.ResponseBuilder.aResponse) SamlValidationResponse(uk.gov.ida.saml.core.validation.SamlValidationResponse) Element(org.w3c.dom.Element) SessionId(uk.gov.ida.common.SessionId) URI(java.net.URI) Test(org.junit.jupiter.api.Test)

Example 97 with Response

use of org.opensaml.saml2.core.Response in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImpl method getGroupingIdentifierList.

@Override
public String[] getGroupingIdentifierList(String loginResponse) {
    if (log.isDebugEnabled()) {
        log.debug("Login response " + loginResponse);
    }
    ByteArrayInputStream samlResponseStream = null;
    DocumentBuilder docBuilder;
    String username = "";
    String organization = "";
    String[] groupIdArray = null;
    try {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI);
        if (StringUtils.isBlank(claim)) {
            claim = "http://wso2.org/claims/organization";
        }
        samlResponseStream = getByteArrayInputStream(loginResponse);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        builderFactory.setNamespaceAware(true);
        docBuilder = builderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(samlResponseStream);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        Response response = (Response) unmarshaller.unmarshall(element);
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
        String isSAML2Enabled = System.getProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION);
        if (!StringUtils.isEmpty(isSAML2Enabled) && Boolean.parseBoolean(isSAML2Enabled)) {
            organization = getOrganizationFromSamlAssertion(assertions);
        } else {
            RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
            String tenantDomain = MultitenantUtils.getTenantDomain(username);
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
            UserStoreManager manager = realm.getUserStoreManager();
            organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
        }
        if (log.isDebugEnabled()) {
            log.debug("User organization " + organization);
        }
        if (organization != null) {
            if (organization.contains(",")) {
                groupIdArray = organization.split(",");
                for (int i = 0; i < groupIdArray.length; i++) {
                    groupIdArray[i] = groupIdArray[i].toString().trim();
                }
            } else {
                organization = organization.trim();
                groupIdArray = new String[] { organization };
            }
        } else {
            // If claim is null then returning a empty string
            groupIdArray = new String[] {};
        }
    } catch (ParserConfigurationException e) {
        String msg = "Error while parsing SAML Assertion";
        log.error(msg, e);
    } catch (UnmarshallingException e) {
        String msg = "Error while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (SAXException e) {
        String msg = "Parsing exception  occur while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (IOException e) {
        String msg = "IO exception happen while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (UserStoreException e) {
        log.error("User store exception occurred for user" + username, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while checking user existence for " + username, e);
    } finally {
        if (samlResponseStream != null) {
            try {
                samlResponseStream.close();
            } catch (IOException e) {
                // Ignore
                log.error("ERROR_CLOSING_STREAM");
            }
        }
    }
    return groupIdArray;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) XSString(org.opensaml.core.xml.schema.XSString) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) Assertion(org.opensaml.saml.saml2.core.Assertion) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) IOException(java.io.IOException) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 98 with Response

use of org.opensaml.saml2.core.Response in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImpl method getGroupingIdentifiers.

public String getGroupingIdentifiers(String loginResponse) {
    if (log.isDebugEnabled()) {
        log.debug("Login response " + loginResponse);
    }
    ByteArrayInputStream samlResponseStream = null;
    DocumentBuilder docBuilder;
    String username = "";
    String organization = "";
    try {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String claim = config.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI);
        if (StringUtils.isBlank(claim)) {
            claim = "http://wso2.org/claims/organization";
        }
        samlResponseStream = getByteArrayInputStream(loginResponse);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        builderFactory.setNamespaceAware(true);
        docBuilder = builderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(samlResponseStream);
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        Response response = (Response) unmarshaller.unmarshall(element);
        List<Assertion> assertions = response.getAssertions();
        if (assertions != null && assertions.size() > 0) {
            Subject subject = assertions.get(0).getSubject();
            if (subject != null) {
                if (subject.getNameID() != null) {
                    username = subject.getNameID().getValue();
                }
            }
        }
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
        UserRealm realm = (UserRealm) realmService.getTenantUserRealm(tenantId);
        UserStoreManager manager = realm.getUserStoreManager();
        organization = manager.getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), claim, null);
        if (log.isDebugEnabled()) {
            log.debug("User organization " + organization);
        }
        if (organization != null) {
            organization = tenantDomain + "/" + organization.trim();
        }
    } catch (ParserConfigurationException e) {
        String msg = "Error while parsing SAML Assertion";
        log.error(msg, e);
    } catch (UnmarshallingException e) {
        String msg = "Error while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (SAXException e) {
        String msg = "Parsing exception  occur while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (IOException e) {
        String msg = "IO exception happen while unmarshalling the SAML Assertion";
        log.error(msg, e);
    } catch (UserStoreException e) {
        log.error("User store exception occurred for user" + username, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("Error while checking user existence for " + username, e);
    } finally {
        if (samlResponseStream != null) {
            try {
                samlResponseStream.close();
            } catch (IOException e) {
                // Ignore
                log.error("ERROR_CLOSING_STREAM");
            }
        }
    }
    return organization;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) XSString(org.opensaml.core.xml.schema.XSString) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) UserRealm(org.wso2.carbon.user.core.UserRealm) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException) Assertion(org.opensaml.saml.saml2.core.Assertion) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) IOException(java.io.IOException) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) ByteArrayInputStream(java.io.ByteArrayInputStream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 99 with Response

use of org.opensaml.saml2.core.Response in project carbon-apimgt by wso2.

the class SAMLGroupIDExtractorImplTest method getGroupingIdentifierListTestCase.

@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException, UnmarshallingException, UserStoreException {
    String claim = "http://wso2.org/claims/organization";
    String organizationValue = "organization";
    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");
    System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).thenReturn("http://wso2.org/claims/organization");
    System.setProperty("carbon.home", "");
    PrivilegedCarbonContext carbonContext;
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
    PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);
    AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
    List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
    PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);
    Attribute mockAttribute = PowerMockito.mock(Attribute.class);
    List<Attribute> attributesList = Collections.singletonList(mockAttribute);
    PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);
    XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
    PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
    List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
    AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName", "namespacePrefix");
    String sampleAttrValue = "MockedAuthParamSampleAttribute";
    mockedAttributedStringImpl.setValue(sampleAttrValue);
    List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
    XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
    PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
    List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
    List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
    AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito.mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
    PowerMockito.when(mockAttribute.getAttributeValues()).thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues, mockedXSAnyImplAttributeValues);
    PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
    AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito.mock(AuthenticatorsConfiguration.class);
    PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
    Map<String, String> mockedConfigParameters = new HashMap<String, String>();
    mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
    PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
    PowerMockito.when(mockedAuthenticatorsConfiguration.getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME)).thenReturn(mockedAuthenticatorConfig);
    PowerMockito.when(mockAttribute.getName()).thenReturn(claim);
    String[] organizations = samlGroupIDExtractor.getGroupingIdentifierList("test");
    Assert.assertEquals(organizationValue, organizations[0]);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Attribute(org.opensaml.saml.saml2.core.Attribute) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) XSAnyImpl(org.opensaml.core.xml.schema.impl.XSAnyImpl) AttributedStringImpl(org.opensaml.soap.wssecurity.impl.AttributedStringImpl) NameID(org.opensaml.saml.saml2.core.NameID) AuthenticatorsConfiguration(org.wso2.carbon.core.security.AuthenticatorsConfiguration) Assertion(org.opensaml.saml.saml2.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Subject(org.opensaml.saml.saml2.core.Subject) Response(org.opensaml.saml.saml2.core.Response) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 100 with Response

use of org.opensaml.saml2.core.Response in project cxf by apache.

the class SAMLSSOResponseValidatorTest method testInvalidAddress.

@org.junit.Test
public void testInvalidAddress() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://bad.apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");
    Response response = createResponse(subjectConfirmationData);
    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
    // expected
    }
}
Also used : Response(org.opensaml.saml.saml2.core.Response) SubjectConfirmationDataBean(org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) DateTime(org.joda.time.DateTime)

Aggregations

Response (org.opensaml.saml.saml2.core.Response)245 Test (org.junit.jupiter.api.Test)148 ResponseBuilder.aResponse (uk.gov.ida.saml.core.test.builders.ResponseBuilder.aResponse)84 Assertion (org.opensaml.saml.saml2.core.Assertion)62 EncryptedAssertion (org.opensaml.saml.saml2.core.EncryptedAssertion)51 Element (org.w3c.dom.Element)44 Status (org.opensaml.saml.saml2.core.Status)37 DateTime (org.joda.time.DateTime)36 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)31 Document (org.w3c.dom.Document)31 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)19 SubjectConfirmationDataBean (org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean)19 SamlValidationResponse (uk.gov.ida.saml.core.validation.SamlValidationResponse)19 IdpIdaStatus (uk.gov.ida.saml.hub.domain.IdpIdaStatus)18 Authentication (org.springframework.security.core.Authentication)16 ResponseValidatorTestHelper.createStatus (uk.gov.ida.saml.hub.validators.response.helpers.ResponseValidatorTestHelper.createStatus)16 Crypto (org.apache.wss4j.common.crypto.Crypto)15 NameID (org.opensaml.saml.saml2.core.NameID)14 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)13