org.apache.wss4j.common.saml.builder.SAML2Constants Java Examples

The following examples show how to use org.apache.wss4j.common.saml.builder.SAML2Constants. 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: SAMLSSOResponseValidator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the Subject (of an Authentication Statement).
 */
private boolean validateAuthenticationSubject(
    org.opensaml.saml.saml2.core.Subject subject, String id, boolean postBinding
) throws WSSecurityException {
    if (subject.getSubjectConfirmations() == null) {
        return false;
    }

    boolean foundBearerSubjectConf = false;
    // We need to find a Bearer Subject Confirmation method
    for (org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf
        : subject.getSubjectConfirmations()) {
        if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
            foundBearerSubjectConf = true;
            validateSubjectConfirmation(subjectConf.getSubjectConfirmationData(), id, postBinding);
        }
    }

    return foundBearerSubjectConf;
}
 
Example #2
Source File: CustomAuthenticationProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Get an AuthenticationStatementBean using the given parameters.
 */
public AuthenticationStatementBean getStatement(TokenProviderParameters providerParameters) {
    AuthenticationStatementBean authBean = new AuthenticationStatementBean();

    SubjectLocalityBean subjectLocality = new SubjectLocalityBean();
    subjectLocality.setIpAddress("127.0.0.1");
    authBean.setSubjectLocality(subjectLocality);

    if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(
            providerParameters.getTokenRequirements().getTokenType())) {
        authBean.setAuthenticationMethod(SAML1Constants.AUTH_METHOD_X509);
    } else {
        authBean.setAuthenticationMethod(SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509);
    }
    return authBean;
}
 
Example #3
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml2 Bearer Assertion.
 */
@org.junit.Test
public void testDefaultSaml2BearerAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertFalse(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
}
 
Example #4
Source File: SAMLSSOResponseValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the Subject (of an Authentication Statement).
 */
private org.opensaml.saml.saml2.core.SubjectConfirmation validateAuthenticationSubject(
    org.opensaml.saml.saml2.core.Subject subject, String id, boolean postBinding
) throws WSSecurityException {
    if (subject.getSubjectConfirmations() == null) {
        return null;
    }

    org.opensaml.saml.saml2.core.SubjectConfirmation validSubjectConf = null;
    // We need to find a Bearer Subject Confirmation method
    for (org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf
        : subject.getSubjectConfirmations()) {
        if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
            validateSubjectConfirmation(subjectConf.getSubjectConfirmationData(), id, postBinding);
            validSubjectConf = subjectConf;
        }
    }

    return validSubjectConf;
}
 
Example #5
Source File: SAMLSSOResponseValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the Issuer (if it exists)
 */
private void validateIssuer(org.opensaml.saml.saml2.core.Issuer issuer) throws WSSecurityException {
    if (issuer == null) {
        return;
    }

    // Issuer value must match (be contained in) Issuer IDP
    if (enforceKnownIssuer && (issuer.getValue() == null || !issuerIDP.startsWith(issuer.getValue()))) {
        LOG.warning("Issuer value: " + issuer.getValue() + " does not match issuer IDP: "
            + issuerIDP);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Format must be nameid-format-entity
    if (issuer.getFormat() != null
        && !SAML2Constants.NAMEID_FORMAT_ENTITY.equals(issuer.getFormat())) {
        LOG.warning("Issuer format is not null and does not equal: "
            + SAML2Constants.NAMEID_FORMAT_ENTITY);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example #6
Source File: SAML2CallbackHandler.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void createAndSetStatement(SAMLCallback callback) {
    AuthenticationStatementBean authBean = new AuthenticationStatementBean();
    authBean.setAuthenticationMethod("Password");
    callback.setAuthenticationStatementData(Collections.singletonList(authBean));

    // Add roles for certain users
    List<Object> roles = new ArrayList<>();
    if ("alice".equals(subjectName)) {
        roles.add("boss");
        roles.add("employee");
        roles.add("User");
    } else if ("bob".equals(subjectName)) {
        roles.add("employee");
    }

    if (!roles.isEmpty()) {
        AttributeStatementBean attrBean = new AttributeStatementBean();
        AttributeBean attributeBean = new AttributeBean();
        attributeBean.setQualifiedName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
        attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
        attributeBean.setAttributeValues(roles);

        attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
        callback.setAttributeStatementData(Collections.singletonList(attrBean));
    }
}
 
Example #7
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean validateAuthenticationSubject(Message m,
                                              Conditions cs,
                                              org.opensaml.saml.saml2.core.Subject subject) {
    // We need to find a Bearer Subject Confirmation method
    boolean bearerSubjectConfFound = false;
    if (subject.getSubjectConfirmations() != null) {
        for (SubjectConfirmation subjectConf : subject.getSubjectConfirmations()) {
            if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
                validateSubjectConfirmation(m, cs, subjectConf.getSubjectConfirmationData());
                bearerSubjectConfFound = true;
            }
        }
    }

    return bearerSubjectConfFound;
}
 
Example #8
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with various Attributes set by a ClaimsHandler.
 * We have both a primary claim (sent in wst:RequestSecurityToken) and a secondary claim
 * (send in wst:RequestSecurityToken/wst:SecondaryParameters), and both have the
 * same dialect in this test.
 */
@org.junit.Test
public void testSaml2MultipleClaimsSameDialect() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection primaryClaims = createClaims();
    primaryClaims.setDialect(ClaimTypes.URI_BASE);
    providerParameters.setRequestedPrimaryClaims(primaryClaims);

    ClaimCollection secondaryClaims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(ClaimTypes.STREETADDRESS);
    secondaryClaims.add(claim);
    secondaryClaims.setDialect(ClaimTypes.URI_BASE);
    providerParameters.setRequestedSecondaryClaims(secondaryClaims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertTrue(tokenString.contains(ClaimTypes.EMAILADDRESS.toString()));
    assertTrue(tokenString.contains(ClaimTypes.FIRSTNAME.toString()));
    assertTrue(tokenString.contains(ClaimTypes.LASTNAME.toString()));
    assertTrue(tokenString.contains(ClaimTypes.STREETADDRESS.toString()));
}
 
Example #9
Source File: SamlTokenTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSaml2OverAsymmetricEncrypted() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = SamlTokenTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = SamlTokenTest.class.getResource("DoubleItSaml.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItSaml2AsymmetricEncryptedPort");
    DoubleItPortType saml2Port =
            service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(saml2Port, test.getPort());

    if (test.isStreaming()) {
        SecurityTestUtil.enableStreaming(saml2Port);
    }

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler(true, true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    ((BindingProvider)saml2Port).getRequestContext().put(
        SecurityConstants.SAML_CALLBACK_HANDLER, callbackHandler
    );
    int result = saml2Port.doubleIt(25);
    assertTrue(result == 50);

    ((java.io.Closeable)saml2Port).close();
    bus.shutdown(true);
}
 
Example #10
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with various Attributes set by a ClaimsHandler.
 * We have both a primary claim (sent in wst:RequestSecurityToken) and a secondary claim
 * (send in wst:RequestSecurityToken/wst:SecondaryParameters).
 */
@org.junit.Test
public void testSaml2MultipleClaims() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection primaryClaims = createClaims();
    providerParameters.setRequestedPrimaryClaims(primaryClaims);

    ClaimCollection secondaryClaims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(ClaimTypes.STREETADDRESS);
    secondaryClaims.add(claim);
    providerParameters.setRequestedSecondaryClaims(secondaryClaims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertTrue(tokenString.contains(ClaimTypes.EMAILADDRESS.toString()));
    assertTrue(tokenString.contains(ClaimTypes.FIRSTNAME.toString()));
    assertTrue(tokenString.contains(ClaimTypes.LASTNAME.toString()));
    assertTrue(tokenString.contains(ClaimTypes.STREETADDRESS.toString()));
}
 
Example #11
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void unsignedAssertionInLoginResponse() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    // Get a valid login request for the Fediz realm
    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);
    SAML2RequestTO loginRequest = saml2Service.createLoginRequest(ADDRESS, "urn:org:apache:cxf:fediz:idp:realm-A");
    assertNotNull(loginRequest);

    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");
    response.setRelayState(loginRequest.getRelayState());

    // Create a SAML Response using WSS4J
    JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
    String inResponseTo = relayState.getJwtClaims().getSubject();

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(inResponseTo, false, SAML2Constants.CONF_SENDER_VOUCHES,
                    "urn:org:apache:cxf:fediz:idp:realm-A");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsigned Assertion");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example #12
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * "Validate" SAML 2 token with a custom token validator
 * If a validator is configured it precedes the SAMLTokenValidator as part of Fediz
 */
@org.junit.Test
public void validateSAML2TokenMaxClockSkewNotDefined() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("NOCLOCKSKEW");

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse wfRes = wfProc.processRequest(wfReq, config);

    Assert.assertEquals("Principal name wrong", TEST_USER,
                        wfRes.getUsername());
    Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
    Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles()
                        .size());
    Assert.assertEquals("Audience wrong", TEST_AUDIENCE, wfRes.getAudience());
}
 
Example #13
Source File: SAML2CallbackHandler.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(Version.SAML_20);
            callback.setIssuer(issuer);
            if (conditions != null) {
                callback.setConditions(conditions);
            }

            SubjectBean subjectBean =
                new SubjectBean(
                    subjectName, subjectQualifier, confirmationMethod
                );
            if (subjectNameIDFormat != null) {
                subjectBean.setSubjectNameIDFormat(subjectNameIDFormat);
            }
            subjectBean.setSubjectConfirmationData(subjectConfirmationData);
            if (SAML2Constants.CONF_HOLDER_KEY.equals(confirmationMethod)) {
                try {
                    KeyInfoBean keyInfo = createKeyInfo();
                    subjectBean.setKeyInfo(keyInfo);
                } catch (Exception ex) {
                    throw new IOException("Problem creating KeyInfo: " +  ex.getMessage());
                }
            }
            callback.setSubject(subjectBean);
            createAndSetStatement(null, callback);
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example #14
Source File: Saml2CallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {

            SAMLCallback callback = (SAMLCallback) callbacks[i];
            callback.setSamlVersion(Version.SAML_20);

            callback.setIssuer("intermediary");
            String subjectName = "uid=" + principal.getName();
            String confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES;

            SubjectBean subjectBean =
                new SubjectBean(subjectName, null, confirmationMethod);
            callback.setSubject(subjectBean);

            AttributeStatementBean attrBean = new AttributeStatementBean();
            if (subjectBean != null) {
                attrBean.setSubject(subjectBean);
            }
            AttributeBean attributeBean = new AttributeBean();
            attributeBean.setQualifiedName("role");
            attributeBean.addAttributeValue("user");
            attrBean.setSamlAttributes(Collections.singletonList(attributeBean));
            callback.setAttributeStatementData(Collections.singletonList(attrBean));

            try {
                String file = "serviceKeystore.properties";
                Crypto crypto = CryptoFactory.getInstance(file);
                callback.setIssuerCrypto(crypto);
                callback.setIssuerKeyName("myservicekey");
                callback.setIssuerKeyPassword("skpass");
                callback.setSignAssertion(true);
            } catch (WSSecurityException e) {
                throw new IOException(e);
            }
        }
    }
}
 
Example #15
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenBadServiceName() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("{http://cxf.apache.org/hello_world_jms}BadHelloWorldService");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    try {
        greeter.sayHi();
        fail("Failure expected on a bad audience restriction");
    } catch (SOAPFaultException ex) {
        // expected
    }

    ((java.io.Closeable)greeter).close();
}
 
Example #16
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenServiceName() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    String response = new String("Bonjour");
    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("{http://cxf.apache.org/hello_world_jms}HelloWorldService");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    String reply = greeter.sayHi();
    assertNotNull("no response received from service", reply);
    assertEquals(response, reply);

    ((java.io.Closeable)greeter).close();
}
 
Example #17
Source File: JMSWSSecurityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsignedSAML2AudienceRestrictionTokenBadURI() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldService");
    QName portName = new QName("http://cxf.apache.org/hello_world_jms", "HelloWorldPort");
    URL wsdl = getWSDLURL("/wsdl/jms_test.wsdl");
    HelloWorldService service = new HelloWorldService(wsdl, serviceName);

    HelloWorldPortType greeter = service.getPort(portName, HelloWorldPortType.class);

    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    callbackHandler.setSignAssertion(true);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);
    List<String> audiences = new ArrayList<>();
    audiences.add("jms:jndi:dynamicQueues/test.jmstransport.text.bad");
    AudienceRestrictionBean audienceRestrictionBean = new AudienceRestrictionBean();
    audienceRestrictionBean.setAudienceURIs(audiences);
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestrictionBean));

    callbackHandler.setConditions(conditions);

    Map<String, Object> outProperties = new HashMap<>();
    outProperties.put(ConfigurationConstants.ACTION, ConfigurationConstants.SAML_TOKEN_UNSIGNED);
    outProperties.put(ConfigurationConstants.SAML_CALLBACK_REF, callbackHandler);

    WSS4JOutInterceptor outInterceptor = new WSS4JOutInterceptor(outProperties);
    Client client = ClientProxy.getClient(greeter);
    client.getOutInterceptors().add(outInterceptor);

    try {
        greeter.sayHi();
        fail("Failure expected on a bad audience restriction");
    } catch (SOAPFaultException ex) {
        // expected
    }

    ((java.io.Closeable)greeter).close();
}
 
Example #18
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate SAML 2 token which includes the role attribute with 2 values
 * The configured subject of the trusted issuer doesn't match with
 * the issuer of the SAML token
 */
@org.junit.Test
public void validateUnsignedSAML2Token() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    String rstr = createSamlToken(assertion, "mystskey", false);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    // Load and update the config to enforce an error
    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        Assert.fail("Processing must fail because of missing signature");
    } catch (ProcessingException ex) {
        if (!TYPE.TOKEN_NO_SIGNATURE.equals(ex.getType())) {
            fail("Expected ProcessingException with TOKEN_NO_SIGNATURE type");
        }
    }
}
 
Example #19
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with StaticClaimsHandler
 */
@org.junit.Test
public void testSaml2StaticClaims() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    StaticClaimsHandler claimsHandler = new StaticClaimsHandler();
    Map<String, String> staticClaimsMap = new HashMap<>();
    staticClaimsMap.put(CLAIM_STATIC_COMPANY, CLAIM_STATIC_COMPANY_VALUE);
    claimsHandler.setGlobalClaims(staticClaimsMap);
    claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(CLAIM_STATIC_COMPANY);
    claims.add(claim);
    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));

    SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
    List<Attribute> attributes = assertion.getSaml2().getAttributeStatements().get(0).getAttributes();
    assertEquals(attributes.size(), 1);
    assertEquals(attributes.get(0).getName(), CLAIM_STATIC_COMPANY);
    XMLObject valueObj = attributes.get(0).getAttributeValues().get(0);
    assertEquals(valueObj.getDOM().getTextContent(), CLAIM_STATIC_COMPANY_VALUE);
}
 
Example #20
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with various Attributes set by a ClaimsHandler.
 */
@org.junit.Test
public void testSaml2ClaimsInteger() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(ClaimTypes.MOBILEPHONE);
    claims.add(claim);
    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertTrue(tokenString.contains(ClaimTypes.MOBILEPHONE.toString()));
}
 
Example #21
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a default Saml2 PublicKey Assertion.
 */
@org.junit.Test
public void testDefaultSaml2PublicKeyAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.SAML2_NS, STSConstants.PUBLIC_KEY_KEYTYPE);
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.SAML2_NS));

    try {
        samlTokenProvider.createToken(providerParameters);
        fail("Failure expected on no certificate");
    } catch (STSException ex) {
        // expected as no certificate is provided
    }

    // Now get a certificate and set it on the key requirements of the provider parameter
    Crypto crypto = providerParameters.getStsProperties().getEncryptionCrypto();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    ReceivedCredential receivedCredential = new ReceivedCredential();
    receivedCredential.setX509Cert(certs[0]);
    providerParameters.getKeyRequirements().setReceivedCredential(receivedCredential);

    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
    assertFalse(tokenString.contains(SAML2Constants.CONF_BEARER));
}
 
Example #22
Source File: CustomSamlValidator.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 returnedCredential = super.validate(credential, data);

    //
    // Do some custom validation on the assertion
    //
    SamlAssertionWrapper assertion = credential.getSamlAssertion();
    if (!"www.example.com".equals(assertion.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (requireSAML1Assertion && assertion.getSaml1() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    } else if (!requireSAML1Assertion && assertion.getSaml2() == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    String confirmationMethod = assertion.getConfirmationMethods().get(0);
    if (confirmationMethod == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    if (requireSenderVouches && !OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    } else if (requireBearer && !(SAML2Constants.CONF_BEARER.equals(confirmationMethod)
        || SAML1Constants.CONF_BEARER.equals(confirmationMethod))) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    } else if (!requireBearer && !requireSenderVouches
        && !OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    return returnedCredential;
}
 
Example #23
Source File: SAMLTokenValidatorOldTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate SAML 2 token where role information is provided
 * within another SAML attribute
 */
@org.junit.Test
public void validateSAML2TokenDifferentRoleURI() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    callbackHandler.setAttributeNameFormat(ClaimTypes.URI_BASE.toString());
    callbackHandler.setCountryClaimName("country");
    callbackHandler.setRoleAttributeName("http://schemas.mycompany.com/claims/role");

    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("CUSTOMROLEURI");

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse wfRes = wfProc.processRequest(wfReq, config);

    Assert.assertEquals("Principal name wrong", TEST_USER, wfRes.getUsername());
    Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
    Assert.assertEquals("Two roles must be found", 2, wfRes.getRoles().size());
    Assert.assertEquals("Audience wrong", TEST_AUDIENCE, wfRes.getAudience());
    assertClaims(wfRes.getClaims(), callbackHandler.getRoleAttributeName());
}
 
Example #24
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * "Validate" SAML 2 token with a custom token validator
 * If a validator is configured it precedes the SAMLTokenValidator as part of Fediz
 */
@org.junit.Test
public void validateSAML2TokenCustomValidator() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("CUSTTOK");
    Protocol protocol = config.getProtocol();
    List<TokenValidator> validators = protocol.getTokenValidators();
    Assert.assertEquals("Two validators must be found", 2, validators.size());
    Assert.assertEquals("First validator must be custom validator",
                        CustomValidator.class.getName(), validators.get(0).getClass().getName());

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse wfRes = wfProc.processRequest(wfReq, config);

    Assert.assertEquals("Principal name wrong", TEST_USER,
                        wfRes.getUsername());
    Assert.assertEquals("Issuer wrong", TEST_RSTR_ISSUER, wfRes.getIssuer());
}
 
Example #25
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateAndValidateResponse() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(marshalledResponse, null, null);
}
 
Example #26
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testRequestDeniedStatusCode() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:RequestDenied", null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid SAML code");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #27
Source File: AudienceRestrictionTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void validateNoAudienceThatIsRequired() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    String rstr = createSamlToken(assertion, "mystskey", true);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("AUD1");

    // Mock up the servet request/response
    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getParameter(FederationConstants.PARAM_HOME_REALM)).andReturn(null);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
    EasyMock.expect(req.getMethod()).andReturn("POST");
    EasyMock.expect(req.getParameter(FederationConstants.PARAM_RESULT)).andReturn(rstr);
    EasyMock.expect(req.getParameter(FederationConstants.PARAM_ACTION))
        .andReturn(FederationConstants.ACTION_SIGNIN);
    EasyMock.expect(req.getParameter("RelayState")).andReturn(null);
    EasyMock.expect(req.getAttribute("javax.servlet.request.X509Certificate")).andReturn(null);
    EasyMock.expect(req.getQueryString()).andReturn(null);
    EasyMock.replay(req);

    HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
    EasyMock.replay(resp);

    // Now validate the request
    TestSigninHandler signinHandler = new TestSigninHandler(config);
    Assert.assertNull(signinHandler.handleRequest(req, resp));
}
 
Example #28
Source File: SAML2CallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public SAML2CallbackHandler() throws Exception {
    if (certs == null) {
        Crypto crypto = CryptoFactory.getInstance("alice.properties");
        CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
        cryptoType.setAlias("alice");
        certs = crypto.getX509Certificates(cryptoType);
    }

    subjectName = "uid=joe,ou=people,ou=saml-demo,o=example.com";
    subjectQualifier = "www.example.com";
    confirmationMethod = SAML2Constants.CONF_SENDER_VOUCHES;
}
 
Example #29
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnableToFindTruststore() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    String rstr = createSamlToken(assertion, "mystskey", true);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("BAD_KEYSTORE");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on being unable to find the truststore");
    } catch (ProcessingException ex) {
        ex.printStackTrace();
        // expected
    }
}
 
Example #30
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate SAML 2 token which includes the role attribute with 2 values
 * The configured subject of the trusted issuer doesn't match with
 * the issuer of the SAML token
 *
 * Ignored because PeerTrust ignores subject attribute
 */
@org.junit.Test
@org.junit.Ignore
public void validateSAML2TokenUntrustedIssuer() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    String rstr = createSamlToken(assertion, "mystskey", true);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    // Load and update the config to enforce an error
    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");
    config.getTrustedIssuers().get(0).setSubject("wrong-issuer-name");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        Assert.fail("Processing must fail because of untrusted issuer configured");
    } catch (ProcessingException ex) {
        if (!TYPE.ISSUER_NOT_TRUSTED.equals(ex.getType())) {
            fail("Expected ProcessingException with ISSUER_NOT_TRUSTED type");
        }
    }
}