org.opensaml.saml.saml2.core.Subject Java Examples

The following examples show how to use org.opensaml.saml.saml2.core.Subject. 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: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * New subject element.
 *
 * @param nameIdFormat the name id format
 * @param nameIdValue the name id value
 * @param recipient the recipient
 * @param notOnOrAfter the not on or after
 * @param inResponseTo the in response to
 * @return the subject
 */
public Subject newSubject(final String nameIdFormat, final String nameIdValue,
                          final String recipient, final DateTime notOnOrAfter,
                          final String inResponseTo) {

    final SubjectConfirmation confirmation = newSamlObject(SubjectConfirmation.class);
    confirmation.setMethod(SubjectConfirmation.METHOD_BEARER);

    final SubjectConfirmationData data = newSamlObject(SubjectConfirmationData.class);
    data.setRecipient(recipient);
    data.setNotOnOrAfter(notOnOrAfter);
    data.setInResponseTo(inResponseTo);

    confirmation.setSubjectConfirmationData(data);

    final Subject subject = newSamlObject(Subject.class);
    subject.setNameID(getNameID(nameIdFormat, nameIdValue));
    subject.getSubjectConfirmations().add(confirmation);
    return subject;
}
 
Example #2
Source File: OnBehalfOfValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Subject subject = saml2Assertion.getSubject();
    NameID nameID = subject.getNameID();
    String subjectName = nameID.getValue();
    if ("alice".equals(subjectName) || "bob".equals(subjectName)) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #3
Source File: AssertionHelper.java    From verify-service-provider with MIT License 6 votes vote down vote up
private static Subject anAssertionSubject(final String inResponseTo, boolean shouldBeExpired) {
    final DateTime notOnOrAfter;
    if (shouldBeExpired) {
        notOnOrAfter = DateTime.now().minusMinutes(5);
    } else {
        notOnOrAfter = DateTime.now().plus(1000000);
    }
    return aSubject()
            .withSubjectConfirmation(
                    aSubjectConfirmation()
                            .withSubjectConfirmationData(
                                    aSubjectConfirmationData()
                                            .withNotOnOrAfter(notOnOrAfter)
                                            .withInResponseTo(inResponseTo)
                                            .build()
                            ).build()
            ).build();
}
 
Example #4
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldThrowExceptionWhenNameIdIsMissing() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("NameID is missing from the subject of the assertion.");

    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().withSubjectConfirmationData(
            aSubjectConfirmationData()
                    .withInResponseTo(IN_RESPONSE_TO)
                    .build()).build();
    Subject subject = aSubject()
            .withSubjectConfirmation(subjectConfirmation)
            .withNameId(null)
            .build();

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #5
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldThrowExceptionWhenInResponseToRequestIdDoesNotMatchTheRequestId() throws Exception {
    String expectedInResponseTo = "some-non-matching-request-id";
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("'InResponseTo' must match requestId. Expected " + expectedInResponseTo + " but was " + IN_RESPONSE_TO);

    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().withSubjectConfirmationData(
            aSubjectConfirmationData()
                    .withInResponseTo(IN_RESPONSE_TO)
                    .build()).build();
    Subject subject = aSubject()
            .withSubjectConfirmation(subjectConfirmation)
            .build();

    subjectValidator.validate(subject, expectedInResponseTo);
}
 
Example #6
Source File: GoogleAccountsService.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Construct SAML response.
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @return the SAML response
 */
private String constructSamlResponse() {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    final RegisteredService svc = this.servicesManager.findServiceBy(this);
    final String userId = svc.getUsernameAttributeProvider().resolveUsername(getPrincipal(), this);

    final org.opensaml.saml.saml2.core.Response response = BUILDER.newResponse(
            BUILDER.generateSecureRandomId(),
            currentDateTime,
            getId(), this);
    response.setStatus(BUILDER.newStatus(StatusCode.SUCCESS, null));

    final AuthnStatement authnStatement = BUILDER.newAuthnStatement(
            AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime);
    final Assertion assertion = BUILDER.newAssertion(authnStatement,
            "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, BUILDER.generateSecureRandomId());

    final Conditions conditions = BUILDER.newConditions(notBeforeIssueInstant,
            currentDateTime, getId());
    assertion.setConditions(conditions);

    final Subject subject = BUILDER.newSubject(NameID.EMAIL, userId,
            getId(), currentDateTime, this.requestId);
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    BUILDER.marshalSamlXmlObject(response, writer);

    final String result = writer.toString();
    logger.debug("Generated Google SAML response: {}", result);
    return result;
}
 
Example #7
Source File: ActAsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // The technical user should be in the Subject
    Subject subject = saml2Assertion.getSubject();
    if (subject == null || subject.getNameID() == null
        || !subject.getNameID().getValue().contains("www.client.com")) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (AttributeStatement statement : attributeStatements) {
        List<Attribute> attributes = statement.getAttributes();
        for (Attribute attribute : attributes) {
            if (!"CustomActAs".equals(attribute.getName()) && !"ActAs".equals(attribute.getName())) {
                continue;
            }
            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (text.contains("alice") || text.contains("bob")) {
                    return validatedCredential;
                }
            }
        }
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #8
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Assertion
 *
 * @param assertion SAML2 assertion
 * @return username
 */
public static String getUsernameFromAssertion(Assertion assertion, String usernameAttribute) {
    String username = null;
    if (!StringUtils.isEmpty(usernameAttribute)) {
        // There can be multiple AttributeStatements in Assertion
        List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
        if (attributeStatements != null) {
            for (AttributeStatement attributeStatement : attributeStatements) {
                // There can be multiple Attributes in an attributeStatement
                List<Attribute> attributes = attributeStatement.getAttributes();
                if (attributes != null) {
                    for (Attribute attribute : attributes) {
                        String attributeName = attribute.getDOM().getAttribute(SSOConstants.SAML_NAME_ATTRIBUTE);
                        if (attributeName.equals(usernameAttribute)) {
                            List<XMLObject> attributeValues = attribute.getAttributeValues();
                            // There can be multiple attribute values in an attribute, but get the first one
                            username = attributeValues.get(0).getDOM().getTextContent();
                            if (log.isDebugEnabled()) {
                                log.debug("Name of authenticated user from SAML response : " + username);
                            }
                        }
                    }
                }
            }
        }
    } else {
        Subject subject = assertion.getSubject();
        if (subject != null) {
            if (subject.getNameID() != null) {
                username = subject.getNameID().getValue();
                if (log.isDebugEnabled()) {
                    log.debug("Name of authenticated user from SAML response : " + username);
                }
            }
        }
    }
    return username;
}
 
Example #9
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenSubjectConfirmationDataHasNoInResponseTo() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Subject confirmation data must contain 'InResponseTo'.");

    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().withSubjectConfirmationData(
            aSubjectConfirmationData()
                    .withInResponseTo(null)
                    .build()).build();
    Subject subject = aSubject()
            .withSubjectConfirmation(subjectConfirmation)
            .build();

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #10
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenSubjectConfirmationDataNotOnOrAfterIsMissing() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Subject confirmation data must contain 'NotOnOrAfter'.");

    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().withSubjectConfirmationData(
            aSubjectConfirmationData().withNotOnOrAfter(null).build()).build();
    Subject subject = aSubject()
            .withSubjectConfirmation(subjectConfirmation)
            .build();

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #11
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenSubjectConfirmationDataMissing() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Subject confirmation data is missing from the assertion.");

    Subject subject = aSubject()
            .withSubjectConfirmation(aSubjectConfirmation().withSubjectConfirmationData(null).build())
            .build();

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #12
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenSubjectConfirmationMethodIsNotBearer() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Subject confirmation method must be 'bearer'.");

    Subject subject = aSubject()
            .withSubjectConfirmation(aSubjectConfirmation().withMethod("anything-but-not-bearer").build())
            .build();

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #13
Source File: SubjectValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenMultipleSubjectConfirmation() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Exactly one subject confirmation is expected.");

    Subject subject = aSubject().build();
    SubjectConfirmation subjectConfirmation = aSubjectConfirmation().build();
    subject.getSubjectConfirmations().addAll(ImmutableList.of(subjectConfirmation, subjectConfirmation));

    subjectValidator.validate(subject, IN_RESPONSE_TO);
}
 
Example #14
Source File: AssertionValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldValidateAssertionSubject() {
    Subject subject = mock(Subject.class, Answers.RETURNS_DEEP_STUBS);
    when(assertion.getSubject()).thenReturn(subject);
    when(subject.getNameID().getValue()).thenReturn("any-value");

    validator.validate(assertion, "some-expected-in-response-to", "any-entity-id");

    verify(subjectValidator).validate(subject, "some-expected-in-response-to");
}
 
Example #15
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static Subject anAssertionSubject(final String inResponseTo) {
    return aSubject()
            .withSubjectConfirmation(
                    aSubjectConfirmation()
                            .withSubjectConfirmationData(
                                    aSubjectConfirmationData()
                                            .withNotOnOrAfter(DateTime.now())
                                            .withInResponseTo(inResponseTo)
                                            .build()
                            ).build()
            ).build();
}
 
Example #16
Source File: BaseEidasAssertionTranslatorTestBase.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static Subject anAssertionSubject(final String inResponseTo) {
    return aSubject()
        .withSubjectConfirmation(
            aSubjectConfirmation()
                .withSubjectConfirmationData(
                    aSubjectConfirmationData()
                        .withNotOnOrAfter(DateTime.now())
                        .withInResponseTo(inResponseTo)
                        .build()
                ).build()
        ).build();
}
 
Example #17
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static Response getAuthResponse(String recipient) throws Exception {
    // IdP entity ID
    final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME);
    issuer.setValue("http://idp.example.com/post");

    final Assertion assertion = build(Assertion.DEFAULT_ELEMENT_NAME);
    final Subject subject = build(Subject.DEFAULT_ELEMENT_NAME);
    final SubjectConfirmation subjectConfirmation = build(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    final SubjectConfirmationData data = build(SubjectConfirmationData.DEFAULT_ELEMENT_NAME);

    data.setInResponseTo(requestIdManager.newId());
    data.setNotOnOrAfter(DateTime.now().plusMinutes(1));
    data.setRecipient(recipient);

    subjectConfirmation.setSubjectConfirmationData(data);
    subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");

    subject.getSubjectConfirmations().add(subjectConfirmation);

    assertion.setSubject(subject);

    assertion.setIssuer(XMLObjectSupport.cloneXMLObject(issuer));
    assertion.setIssueInstant(DateTime.now());
    assertion.setID(requestIdManager.newId());

    final AuthnStatement authnStatement = build(AuthnStatement.DEFAULT_ELEMENT_NAME);
    authnStatement.setSessionIndex("1");
    assertion.getAuthnStatements().add(authnStatement);

    final Conditions conditions = build(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(DateTime.now().minusMinutes(1));
    conditions.setNotOnOrAfter(DateTime.now().plusMinutes(1));

    final AudienceRestriction audienceRestriction = build(AudienceRestriction.DEFAULT_ELEMENT_NAME);
    final Audience audience = build(Audience.DEFAULT_ELEMENT_NAME);
    // Set SP entity ID as an audience.
    audience.setAudienceURI(spEntityId);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictions().add(audienceRestriction);

    assertion.setConditions(conditions);

    sign(assertion, idpCredential, signatureAlgorithm);

    final Response response = build(Response.DEFAULT_ELEMENT_NAME);
    response.getAssertions().add(assertion);

    response.setID(requestIdManager.newId());
    response.setIssuer(issuer);
    response.setIssueInstant(DateTime.now());

    final Status status = build(Status.DEFAULT_ELEMENT_NAME);
    final StatusCode statusCode = build(StatusCode.DEFAULT_ELEMENT_NAME);
    statusCode.setValue(StatusCode.SUCCESS);
    status.setStatusCode(statusCode);
    response.setStatus(status);

    return response;
}
 
Example #19
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void getGroupingIdentifiersTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    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);

    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");

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    Mockito.when(tenantManager.getTenantId("carbon.super")).thenReturn(1234);
    Mockito.when(realmService.getTenantUserRealm(1234)).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getUserClaimValue(MultitenantUtils.
            getTenantAwareUsername("user"), "http://wso2.org/claims/organization", null)).
            thenReturn("organization");

    Assert.assertEquals("carbon.super/organization",samlGroupIDExtractor.
            getGroupingIdentifiers("test"));
}
 
Example #20
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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]);
}
 
Example #21
Source File: SubjectValidator.java    From verify-service-provider with MIT License 4 votes vote down vote up
public void validate(Subject subject, String expectedInResponseTo) {
    if (subject == null) {
        throw new SamlResponseValidationException("Subject is missing from the assertion.");
    }

    if (subject.getSubjectConfirmations().size() != 1) {
        throw new SamlResponseValidationException("Exactly one subject confirmation is expected.");
    }

    SubjectConfirmation subjectConfirmation = subject.getSubjectConfirmations().get(0);
    if (!METHOD_BEARER.equals(subjectConfirmation.getMethod())) {
        throw new SamlResponseValidationException("Subject confirmation method must be 'bearer'.");
    }

    SubjectConfirmationData subjectConfirmationData = subjectConfirmation.getSubjectConfirmationData();
    if (subjectConfirmationData == null) {
        throw new SamlResponseValidationException("Subject confirmation data is missing from the assertion.");
    }

    timeRestrictionValidator.validateNotBefore(subjectConfirmationData.getNotBefore());

    DateTime notOnOrAfter = subjectConfirmationData.getNotOnOrAfter();
    if (notOnOrAfter == null) {
        throw new SamlResponseValidationException("Subject confirmation data must contain 'NotOnOrAfter'.");
    }

    timeRestrictionValidator.validateNotOnOrAfter(notOnOrAfter);

    String actualInResponseTo = subjectConfirmationData.getInResponseTo();
    if (actualInResponseTo == null) {
        throw new SamlResponseValidationException("Subject confirmation data must contain 'InResponseTo'.");
    }

    if (!expectedInResponseTo.equals(actualInResponseTo)) {
        throw new SamlResponseValidationException(String.format("'InResponseTo' must match requestId. Expected %s but was %s", expectedInResponseTo, actualInResponseTo));
    }

    if (subject.getNameID() == null) {
        throw new SamlResponseValidationException("NameID is missing from the subject of the assertion.");
    }
}
 
Example #22
Source File: SAML2CallbackHandler.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public Subject getSubject() {
    return subject;
}
 
Example #23
Source File: SAML2CallbackHandler.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public void setSubject(Subject subject) {
    this.subject = subject;
}