Java Code Examples for org.apache.wss4j.common.saml.SAMLUtil#doSAMLCallback()

The following examples show how to use org.apache.wss4j.common.saml.SAMLUtil#doSAMLCallback() . 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: SamlRetrievalInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {

    // Create a SAML Token
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(new SamlCallbackHandler(), samlCallback);

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        Document doc = DOMUtils.createDocument();
        Element token = assertion.toDOM(doc);
        message.put(SAMLConstants.SAML_TOKEN_ELEMENT, token);
    } catch (WSSecurityException ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 2
Source File: SAMLResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlResponseStr(AbstractSAMLCallbackHandler saml2CallbackHandler,
                                     String requestId) throws Exception {
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_REQUEST_URL);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    saml2CallbackHandler.setConditions(cp);

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    saml2CallbackHandler.setSubjectConfirmationData(subjectConfirmationData);

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

    Element response = createSamlResponse(assertion, "mystskey", true, requestId);
    return encodeResponse(response);
}
 
Example 3
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
 * Roles are encoded as a multi-value saml attribute
 * Not RequestedSecurityTokenCollection in this test, default in all others
 */
@org.junit.Test
public void validateSAML2TokenRSTR() 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, STSUtil.SAMPLE_RSTR_MSG);

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

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

    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 4
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Response createResponse(
    SubjectConfirmationDataBean subjectConfirmationData,
    SAML2CallbackHandler callbackHandler
) 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
    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);

    return (Response)OpenSAMLUtil.fromDom(policyElement);
}
 
Example 5
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
/**
 * Validate an encrypted SAML 2 token which includes the role attribute with 2 values
 * Roles are encoded as a multi-value saml attribute
 */
@org.junit.Test
public void validateEncryptedSAML2Token() 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 = encryptAndSignToken(assertion);

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

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

    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 6
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 validateSAML2TokenSeveralCertStoreTrustedIssuer() 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("ROOT3");

    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());
}
 
Example 7
Source File: SAMLTokenProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SamlAssertionWrapper createSamlToken(
    TokenProviderParameters tokenParameters, byte[] secret, Document doc
) throws Exception {
    String realm = tokenParameters.getRealm();
    RealmProperties samlRealm = null;
    if (realm != null && realmMap.containsKey(realm)) {
        samlRealm = realmMap.get(realm);
    }

    SamlCallbackHandler handler = createCallbackHandler(tokenParameters, secret, samlRealm, doc);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(handler, samlCallback);

    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    if (samlCustomHandler != null) {
        samlCustomHandler.handle(assertion, tokenParameters);
    }

    if (signToken) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        signToken(assertion, samlRealm, stsProperties, tokenParameters.getKeyRequirements());
    }

    return assertion;
}
 
Example 8
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 9
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 validateSAML2TokenSeveralCertStore() 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("ROOT2");

    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());
}
 
Example 10
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void validateSAML2TokenWithConfigCreatedWithAPI() throws Exception {

    ContextConfig config = new ContextConfig();

    config.setName("whatever");

    // Configure certificate store
    CertificateStores certStores = new CertificateStores();
    TrustManagersType tm0 = new TrustManagersType();
    KeyStoreType ks0 = new KeyStoreType();
    ks0.setType("JKS");
    ks0.setPassword("storepass");
    ks0.setFile("ststrust.jks");
    tm0.setKeyStore(ks0);
    certStores.getTrustManager().add(tm0);
    config.setCertificateStores(certStores);

    // Configure trusted IDP
    TrustedIssuers trustedIssuers = new TrustedIssuers();
    TrustedIssuerType ti0 = new TrustedIssuerType();
    ti0.setCertificateValidation(ValidationType.CHAIN_TRUST);
    ti0.setName("FedizSTSIssuer");
    ti0.setSubject(".*CN=www.sts.com.*");
    trustedIssuers.getIssuer().add(ti0);
    config.setTrustedIssuers(trustedIssuers);

    FederationProtocolType protocol = new FederationProtocolType();
    config.setProtocol(protocol);

    AudienceUris audienceUris = new AudienceUris();
    audienceUris.getAudienceItem().add("https://localhost/fedizhelloworld");
    config.setAudienceUris(audienceUris);

    protocol.setRoleURI("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");

    FedizContext fedContext = new FedizContext(config);

    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, STSUtil.SAMPLE_RSTR_MSG);

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

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

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

    fedContext.close();

}
 
Example 11
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNotOnOfAfter() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    RequestState requestState = new RequestState(TEST_REQUEST_URL,
                                                 TEST_IDP_ISSUER,
                                                 requestId,
                                                 TEST_REQUEST_URL,
                                                 (String)config.getProtocol().getIssuer(),
                                                 null,
                                                 relayState,
                                                 System.currentTimeMillis());

    // Create SAML Response
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setAlsoAddAuthnStatement(true);
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_IDP_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);

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

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Element response = createSamlResponse(assertion, "mystskey", true, requestId, null);
    String responseStr = encodeResponse(response);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getRemoteAddr()).andReturn(TEST_CLIENT_ADDRESS);
    EasyMock.replay(req);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setResponseToken(responseStr);
    wfReq.setState(relayState);
    wfReq.setRequest(req);
    wfReq.setRequestState(requestState);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected");
    } catch (ProcessingException ex) {
        if (!TYPE.INVALID_REQUEST.equals(ex.getType())) {
            fail("Expected ProcessingException with INVALID_REQUEST type");
        }
    }
}
 
Example 12
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testModifiedSignature() 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);

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);
    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    // Change IssueInstant attribute
    String issueInstance = token.getAttributeNS(null, "IssueInstant");
    DateTime issueDateTime = new DateTime(issueInstance, DateTimeZone.UTC);
    issueDateTime = issueDateTime.plusSeconds(1);
    token.setAttributeNS(null, "IssueInstant", issueDateTime.toString());

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                   FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                               FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    String rstr = DOM2Writer.nodeToString(doc);

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

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

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on signature validation");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 13
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
                                       String requestID, String requestIssuer,
                                       String remoteAddr, String racs) throws Exception {
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    callbackHandler.setIssuer(issuer);
    callbackHandler.setSubject(receivedToken.getSaml2().getSubject());

    // Test Subject against received Subject (if applicable)
    SAMLAuthnRequest authnRequest =
        (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
    if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
        NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
        if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
            LOG.debug("Received NameID value of {} does not match issued value {}",
                      authnRequest.getSubjectNameId(), issuedNameId.getValue());
            throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
        }
    }

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(remoteAddr);
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    // Attributes
    callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());

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

    Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
    assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(),
                            issuerCrypto, false);

    return assertion.getSaml2();
}
 
Example 14
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2MultipleClaims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");

    AttributeBean attributeBean2 = new AttributeBean();
    attributeBean2.setQualifiedName(
            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
    attributeBean2.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean2.addAttributeValue("smith");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    List<AttributeBean> attributes = new ArrayList<>();
    attributes.add(attributeBean);
    attributes.add(attributeBean2);
    samlCallbackHandler.setAttributes(attributes);

    // Create the SAML Assertion via the CallbackHandler
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);
    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);

    Document doc = DOMUtils.newDocument();
    samlAssertion.toDOM(doc);

    ClaimCollection claims = SAMLUtils.getClaims(samlAssertion);
    assertEquals(claims.getDialect().toString(),
            "http://schemas.xmlsoap.org/ws/2005/05/identity");
    assertEquals(2, claims.size());

    // Check roles
    Set<Principal> roles =
            SAMLUtils.parseRolesFromClaims(claims,
                    SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT,
                    SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    assertEquals(1, roles.size());
    Principal p = roles.iterator().next();
    assertEquals("employee", p.getName());
}
 
Example 15
Source File: ClaimsProcessorTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private FedizResponse performLogin(String claimType, boolean setClaimNameFormat,
                                   String claimValue, String claimsProcessorClass)
        throws WSSecurityException, IOException, UnsupportedCallbackException, JAXBException, ProcessingException,
        SAXException, ParserConfigurationException {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(ISSUER);
    callbackHandler.setSubjectName("alice");
    if (setClaimNameFormat) {
        callbackHandler.setAttributeNameFormat(ClaimTypes.URI_BASE.toString());
    }
    callbackHandler.setCustomClaimName(claimType);
    callbackHandler.setCustomAttributeValues(Collections.singletonList(claimValue));

    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(AUDIENCE_URI_1);
    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);

    FedizConfig config = createConfiguration(claimsProcessorClass);
    StringWriter writer = new StringWriter();
    final JAXBContext jaxbContext = JAXBContext.newInstance(FedizConfig.class);
    jaxbContext.createMarshaller().marshal(config, writer);
    StringReader reader = new StringReader(writer.toString());

    FedizConfigurator configurator = new FedizConfigurator();
    configurator.loadConfig(reader);
    FedizContext context = configurator.getFedizContext(CONFIG_NAME);

    FedizProcessor wfProc = new FederationProcessorImpl();
    return wfProc.processRequest(wfReq, context);
}
 
Example 16
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNoBearerSubjectConfirmation() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    RequestState requestState = new RequestState(TEST_REQUEST_URL,
                                                 TEST_IDP_ISSUER,
                                                 requestId,
                                                 TEST_REQUEST_URL,
                                                 (String)config.getProtocol().getIssuer(),
                                                 null,
                                                 relayState,
                                                 System.currentTimeMillis());

    // Create SAML Response
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setAlsoAddAuthnStatement(true);
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    callbackHandler.setIssuer(TEST_IDP_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);

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

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Element response = createSamlResponse(assertion, "mystskey", true, requestId, null);
    String responseStr = encodeResponse(response);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getRemoteAddr()).andReturn(TEST_CLIENT_ADDRESS);
    EasyMock.replay(req);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setResponseToken(responseStr);
    wfReq.setState(relayState);
    wfReq.setRequest(req);
    wfReq.setRequestState(requestState);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected");
    } catch (ProcessingException ex) {
        if (!TYPE.INVALID_REQUEST.equals(ex.getType())) {
            fail("Expected ProcessingException with INVALID_REQUEST type");
        }
    }
}
 
Example 17
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate SAML 2 token twice which causes an exception
 * due to replay attack
 */
@org.junit.Test
public void testReplayAttack() 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("ROOT");

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

    wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on a replay attack");
    } catch (ProcessingException ex) {
        if (!TYPE.TOKEN_REPLAY.equals(ex.getType())) {
            fail("Expected ProcessingException with TOKEN_REPLAY type");
        }
    }
}
 
Example 18
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testFutureAuthnInstant() 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);
    callbackHandler.setAuthnInstant(new DateTime().plusDays(1));

    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 Assertion AuthnInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 19
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNoAuthnStatement() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    RequestState requestState = new RequestState(TEST_REQUEST_URL,
                                                 TEST_IDP_ISSUER,
                                                 requestId,
                                                 TEST_REQUEST_URL,
                                                 (String)config.getProtocol().getIssuer(),
                                                 null,
                                                 relayState,
                                                 System.currentTimeMillis());

    // Create SAML Response
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_IDP_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);

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

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Element response = createSamlResponse(assertion, "mystskey", true, requestId, null);
    String responseStr = encodeResponse(response);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getRemoteAddr()).andReturn(TEST_CLIENT_ADDRESS);
    EasyMock.replay(req);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setResponseToken(responseStr);
    wfReq.setState(relayState);
    wfReq.setRequest(req);
    wfReq.setRequestState(requestState);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected");
    } catch (ProcessingException ex) {
        if (!TYPE.INVALID_REQUEST.equals(ex.getType())) {
            fail("Expected ProcessingException with INVALID_REQUEST type");
        }
    }
}
 
Example 20
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testNonMatchingAddress() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    RequestState requestState = new RequestState(TEST_REQUEST_URL,
                                                 TEST_IDP_ISSUER,
                                                 requestId,
                                                 TEST_REQUEST_URL,
                                                 (String)config.getProtocol().getIssuer(),
                                                 null,
                                                 relayState,
                                                 System.currentTimeMillis());

    // Create SAML Response
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setAlsoAddAuthnStatement(true);
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_IDP_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);

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

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS + "xyz");
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
    Element response = createSamlResponse(assertion, "mystskey", true, requestId, null);
    String responseStr = encodeResponse(response);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getRemoteAddr()).andReturn(TEST_CLIENT_ADDRESS);
    EasyMock.replay(req);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setResponseToken(responseStr);
    wfReq.setState(relayState);
    wfReq.setRequest(req);
    wfReq.setRequestState(requestState);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected");
    } catch (ProcessingException ex) {
        if (!TYPE.INVALID_REQUEST.equals(ex.getType())) {
            fail("Expected ProcessingException with INVALID_REQUEST type");
        }
    }
}