Java Code Examples for org.apache.wss4j.common.saml.SamlAssertionWrapper#toDOM()

The following examples show how to use org.apache.wss4j.common.saml.SamlAssertionWrapper#toDOM() . 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: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSAML2BearerGrant() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);

    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
    String audienceURI = "https://localhost:" + port + "/oauth2/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
                                                                      signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);

    Saml2BearerGrant grant = new Saml2BearerGrant(assertion);
    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                    new Consumer("alice", "alice"),
                                    grant,
                                    false);
    assertNotNull(at.getTokenKey());
}
 
Example 3
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    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);
    return DOM2Writer.nodeToString(doc);
}
 
Example 4
Source File: RequestedClaimsTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    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);
    return DOM2Writer.nodeToString(doc);
}
 
Example 5
Source File: SAMLTokenValidatorOldTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    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);
    return DOM2Writer.nodeToString(doc);
}
 
Example 6
Source File: ClaimsProcessorTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, SAXException,
    ParserConfigurationException {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    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);
    return DOM2Writer.nodeToString(doc);
}
 
Example 7
Source File: SamlHeaderOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 8
Source File: AudienceRestrictionTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    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);
    return DOM2Writer.nodeToString(doc);
}
 
Example 9
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSAML1Claims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setSimpleName("role");
    attributeBean.setQualifiedName("http://schemas.xmlsoap.org/ws/2005/05/identity/claims");
    attributeBean.addAttributeValue("employee");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // 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(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(1, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals("role", ((SAMLClaim)claim).getName());

    // Check roles
    Set<Principal> roles = SAMLUtils.parseRolesFromClaims(claims, "role", null);
    assertEquals(1, roles.size());
    Principal p = roles.iterator().next();
    assertEquals("employee", p.getName());

}
 
Example 10
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createResponseWithMultipleAssertions(SamlAssertionWrapper assertion1,
                                      boolean signFirstAssertion,
                                      SamlAssertionWrapper assertion2,
                                      boolean signSecondAssertion,
                                      String alias) throws Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (signFirstAssertion) {
        assertion1.signAssertion(alias, password, crypto, false);
    }
    if (signSecondAssertion) {
        assertion2.signAssertion(alias, password, crypto, false);
    }

    Document doc = STSUtil.toSOAPPart(SAMPLE_MULTIPLE_RSTR_COLL_MSG);
    Element token1 = assertion1.toDOM(doc);
    Element token2 = assertion2.toDOM(doc);

    List<Element> requestedTokenElements =
        XMLUtils.findElements(doc, "RequestedSecurityToken", FederationConstants.WS_TRUST_13_NS);
    Assert.assertEquals(2, requestedTokenElements.size());
    requestedTokenElements.get(0).appendChild(token1);
    requestedTokenElements.get(1).appendChild(token2);

    return doc.getDocumentElement();
}
 
Example 11
Source File: SamlEnvelopedOutInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Document createEnvelopedSamlToken(Message message, Document payloadDoc)
    throws Exception {

    Element docEl = payloadDoc.getDocumentElement();
    SamlAssertionWrapper assertion = SAMLUtils.createAssertion(message);

    QName rootName = DOMUtils.getElementQName(payloadDoc.getDocumentElement());
    if (rootName.equals(envelopeQName)) {
        docEl.appendChild(assertion.toDOM(payloadDoc));
        return payloadDoc;
    }

    Document newDoc = DOMUtils.createDocument();

    Element root =
        newDoc.createElementNS(envelopeQName.getNamespaceURI(),
                envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart());
    newDoc.appendChild(root);

    Element assertionEl = assertion.toDOM(newDoc);
    root.appendChild(assertionEl);

    payloadDoc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    root.appendChild(docEl);

    if (signLater) {
        // It appears adopting and removing nodes
        // leaves some stale refs/state with adopted nodes and thus the digest ends up
        // being wrong on the server side if XML sig is applied later in the enveloped mode
        // TODO: this is not critical now - but figure out if we can avoid copying
        // DOMs
        CachedOutputStream bos = new CachedOutputStream();
        StaxUtils.writeTo(newDoc, bos);
        return StaxUtils.read(bos.getInputStream());
    }
    return newDoc;
}
 
Example 12
Source File: SamlElementCallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Mock up a SAML Assertion by using another SAMLCallbackHandler
 * @throws Exception
 */
private Element getSAMLAssertion(Document doc) throws Exception {
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(new SamlCallbackHandler(saml2), samlCallback);
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(samlCallback);

    return assertionWrapper.toDOM(doc);
}
 
Example 13
Source File: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSAML2BearerAuthenticationDirect() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);

    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setIssuer("alice");
    String audienceURI = "https://localhost:" + port + "/oauth2-auth/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
                                                                      signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);

    String encodedAssertion = Base64UrlUtility.encode(assertion);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                                           new CustomGrant(),
                                                           extraParams);
    assertNotNull(at.getTokenKey());
}
 
Example 14
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private String encryptAndSignToken(
    SamlAssertionWrapper assertion
) throws Exception {

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

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

    WSSecEncrypt builder = new WSSecEncrypt(token.getOwnerDocument());
    builder.setUserInfo("mystskey");

    builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
    builder.setKeyEncAlgo(WSConstants.KEYTRANSPORT_RSAOAEP);
    builder.setEmbedEncryptedKey(true);

    WSEncryptionPart encryptionPart = new WSEncryptionPart(assertion.getId(), "Element");
    encryptionPart.setElement(token);

    Crypto encrCrypto = CryptoFactory.getInstance("signature.properties");
    builder.prepare(encrCrypto);
    builder.encryptForRef(null, Collections.singletonList(encryptionPart));

    // return doc.getDocumentElement();
    return DOM2Writer.nodeToString(doc);
}
 
Example 15
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2MultipleRoles() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");
    attributeBean.addAttributeValue("boss");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // 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(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(2, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));
    assertTrue(claim.getValues().contains("boss"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT, ((SAMLClaim)claim).getName());
    assertEquals(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED, ((SAMLClaim)claim).getNameFormat());

    // Check roles
    Set<Principal> roles =
            SAMLUtils.parseRolesFromClaims(claims,
                    SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT,
                    SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    assertEquals(2, roles.size());
}
 
Example 16
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAML2Claims() throws Exception {
    AttributeBean attributeBean = new AttributeBean();
    attributeBean.setQualifiedName(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    attributeBean.setNameFormat(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED);
    attributeBean.addAttributeValue("employee");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler();
    samlCallbackHandler.setAttributes(Collections.singletonList(attributeBean));

    // 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(1, claims.size());

    // Check Claim values
    Claim claim = claims.get(0);
    assertEquals(claim.getClaimType(), SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT);
    assertEquals(1, claim.getValues().size());
    assertTrue(claim.getValues().contains("employee"));

    // Check SAMLClaim values
    assertTrue(claim instanceof SAMLClaim);
    assertEquals(SAMLClaim.SAML_ROLE_ATTRIBUTENAME_DEFAULT, ((SAMLClaim)claim).getName());
    assertEquals(SAML2Constants.ATTRNAME_FORMAT_UNSPECIFIED, ((SAMLClaim)claim).getNameFormat());

    // 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 17
Source File: SAMLTokenProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    testKeyType(tokenParameters);
    KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }

    byte[] secret = null;
    byte[] entropyBytes = null;
    long keySize = 0;
    boolean computedKey = false;
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyRequirements.getKeyType())) {
        SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
        keyHandler.createSymmetricKey();
        secret = keyHandler.getSecret();
        entropyBytes = keyHandler.getEntropyBytes();
        keySize = keyHandler.getKeySize();
        computedKey = keyHandler.isComputedKey();
    }

    try {
        Document doc = DOMUtils.createDocument();
        SamlAssertionWrapper assertion = createSamlToken(tokenParameters, secret, doc);
        Element token = assertion.toDOM(doc);

        // set the token in cache (only if the token is signed)
        byte[] signatureValue = assertion.getSignatureValue();
        if (tokenParameters.getTokenStore() != null && signatureValue != null
            && signatureValue.length > 0) {

            SecurityToken securityToken =
                CacheUtils.createSecurityTokenForStorage(token, assertion.getId(),
                    assertion.getNotOnOrAfter(), tokenParameters.getPrincipal(), tokenParameters.getRealm(),
                    tokenParameters.getTokenRequirements().getRenewing());
            CacheUtils.storeTokenInCache(
                securityToken, tokenParameters.getTokenStore(), signatureValue);
        }

        TokenProviderResponse response = new TokenProviderResponse();

        String tokenType = tokenRequirements.getTokenType();
        if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSS4JConstants.SAML2_NS.equals(tokenType)) {
            response.setTokenId(token.getAttributeNS(null, "ID"));
        } else {
            response.setTokenId(token.getAttributeNS(null, "AssertionID"));
        }

        if (tokenParameters.isEncryptToken()) {
            token = TokenProviderUtils.encryptToken(token, response.getTokenId(),
                                                    tokenParameters.getStsProperties(),
                                                    tokenParameters.getEncryptionProperties(),
                                                    keyRequirements,
                                                    tokenParameters.getMessageContext());
        }
        response.setToken(token);

        DateTime validFrom = null;
        DateTime validTill = null;
        if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = assertion.getSaml2().getConditions().getNotBefore();
            validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = assertion.getSaml1().getConditions().getNotBefore();
            validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());

        response.setEntropy(entropyBytes);
        if (keySize > 0) {
            response.setKeySize(keySize);
        }
        response.setComputedKey(computedKey);

        LOG.fine("SAML Token successfully created");
        if (secret != null) {
            Arrays.fill(secret, (byte) 0);
        }
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
 
Example 18
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Renew a token given a TokenRenewerParameters
 */
public TokenRenewerResponse renewToken(TokenRenewerParameters tokenParameters) {
    TokenRenewerResponse response = new TokenRenewerResponse();
    ReceivedToken tokenToRenew = tokenParameters.getToken();
    if (tokenToRenew == null || tokenToRenew.getToken() == null
        || (tokenToRenew.getState() != STATE.EXPIRED && tokenToRenew.getState() != STATE.VALID)) {
        LOG.log(Level.WARNING, "The token to renew is null or invalid");
        throw new STSException(
            "The token to renew is null or invalid", STSException.INVALID_REQUEST
        );
    }

    TokenStore tokenStore = tokenParameters.getTokenStore();
    if (tokenStore == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SAMLTokenRenewer");
        throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
    }

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper((Element)tokenToRenew.getToken());

        byte[] oldSignature = assertion.getSignatureValue();
        int hash = Arrays.hashCode(oldSignature);
        SecurityToken cachedToken = tokenStore.getToken(Integer.toString(hash));
        if (cachedToken == null) {
            LOG.log(Level.FINE, "The token to be renewed must be stored in the cache");
            throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
        }

        // Validate the Assertion
        validateAssertion(assertion, tokenToRenew, cachedToken, tokenParameters);

        SamlAssertionWrapper renewedAssertion = new SamlAssertionWrapper(assertion.getSamlObject());
        String oldId = createNewId(renewedAssertion);
        // Remove the previous token (now expired) from the cache
        tokenStore.remove(oldId);
        tokenStore.remove(Integer.toString(hash));

        // Create new Conditions & sign the Assertion
        createNewConditions(renewedAssertion, tokenParameters);
        signAssertion(renewedAssertion, tokenParameters);

        Document doc = DOMUtils.createDocument();
        Element token = renewedAssertion.toDOM(doc);
        if (renewedAssertion.getSaml1() != null) {
            token.setIdAttributeNS(null, "AssertionID", true);
        } else {
            token.setIdAttributeNS(null, "ID", true);
        }
        doc.appendChild(token);

        // Cache the token
        storeTokenInCache(
            tokenStore, renewedAssertion, tokenParameters.getPrincipal(), tokenParameters
        );

        response.setToken(token);
        response.setTokenId(renewedAssertion.getId());

        DateTime validFrom = null;
        DateTime validTill = null;
        if (renewedAssertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = renewedAssertion.getSaml2().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = renewedAssertion.getSaml1().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());

        LOG.fine("SAML Token successfully renewed");
        return response;
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "", ex);
        throw new STSException("Can't renew SAML assertion", ex, STSException.REQUEST_FAILED);
    }
}
 
Example 19
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testWrappingAttack() throws Exception {
    // First assertion
    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 assertion1 = new SamlAssertionWrapper(samlCallback);

    // Second assertion
    SAML2CallbackHandler callbackHandler2 = new SAML2CallbackHandler();
    callbackHandler2.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler2.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler2.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler2.setSubjectName("bob");
    ConditionsBean cp2 = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction2 = new AudienceRestrictionBean();
    audienceRestriction2.getAudienceURIs().add(TEST_AUDIENCE);
    cp2.setAudienceRestrictions(Collections.singletonList(audienceRestriction2));
    callbackHandler2.setConditions(cp2);

    SAMLCallback samlCallback2 = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler2, samlCallback2);
    SamlAssertionWrapper assertion2 = new SamlAssertionWrapper(samlCallback2);

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

    assertion1.signAssertion("mystskey", password, crypto, false);
    assertion2.signAssertion("mystskey", password, crypto, false);

    Document doc = STSUtil.toSOAPPart(SAMPLE_MULTIPLE_RSTR_COLL_MSG);
    Element token1 = assertion2.toDOM(doc);
    Element token2 = assertion1.toDOM(doc);

    // Now modify the first Signature to point to the other Element
    Element sig1 = XMLUtils.findElement(token1, "Signature", WSConstants.SIG_NS);
    Element sig2 = XMLUtils.findElement(token2, "Signature", WSConstants.SIG_NS);
    sig1.getParentNode().replaceChild(sig2.cloneNode(true), sig1);

    List<Element> requestedTokenElements =
        XMLUtils.findElements(doc, "RequestedSecurityToken", FederationConstants.WS_TRUST_13_NS);
    Assert.assertEquals(2, requestedTokenElements.size());
    requestedTokenElements.get(0).appendChild(token1);
    requestedTokenElements.get(1).appendChild(token2);

    Element rstrElement = doc.getDocumentElement();

    String rstr = DOM2Writer.nodeToString(rstrElement);
    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 bad signature");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 20
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a HolderOfKey SAML 2 token
 */
@org.junit.Test
public void validateHOKSAML2Token() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    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);

    Crypto clientCrypto = CryptoFactory.getInstance("client-crypto.properties");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = clientCrypto.getX509Certificates(cryptoType);
    callbackHandler.setCerts(certs);

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

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

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on missing client certs");
    } catch (ProcessingException ex) {
        // expected
    }

    // Now set client certs
    wfReq.setCerts(certs);
    wfProc.processRequest(wfReq, config);
}