Search in sources :

Example 21 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class SAMLClaimsTest method testSAML2Claims.

@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(), URI.create(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());
}
Also used : SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) Document(org.w3c.dom.Document) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) Claim(org.apache.cxf.rt.security.claims.Claim) Principal(java.security.Principal)

Example 22 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class SAMLClaimsTest method testSAML1Claims.

@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(), URI.create(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());
}
Also used : SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) SAMLCallback(org.apache.wss4j.common.saml.SAMLCallback) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) Document(org.w3c.dom.Document) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) Claim(org.apache.cxf.rt.security.claims.Claim) Principal(java.security.Principal)

Example 23 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class ActAsAttributeStatementProvider method handleAdditionalParameters.

/**
 * Handle an ActAs element.
 */
private AttributeBean handleAdditionalParameters(Object parameter, String tokenType) throws WSSecurityException {
    AttributeBean parameterBean = new AttributeBean();
    String claimType = "ActAs";
    if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
        parameterBean.setSimpleName(claimType);
        parameterBean.setQualifiedName("http://cxf.apache.org/sts");
    } else {
        parameterBean.setQualifiedName(claimType);
        parameterBean.setNameFormat("http://cxf.apache.org/sts");
    }
    if (parameter instanceof UsernameTokenType) {
        parameterBean.addAttributeValue(((UsernameTokenType) parameter).getUsername().getValue());
    } else if (parameter instanceof Element) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper((Element) parameter);
        SAMLTokenPrincipal principal = new SAMLTokenPrincipalImpl(wrapper);
        parameterBean.addAttributeValue(principal.getName());
        // Check for other ActAs attributes here + add them in
        if (wrapper.getSaml2() != null) {
            for (org.opensaml.saml.saml2.core.AttributeStatement attributeStatement : wrapper.getSaml2().getAttributeStatements()) {
                for (org.opensaml.saml.saml2.core.Attribute attribute : attributeStatement.getAttributes()) {
                    if ("ActAs".equals(attribute.getName())) {
                        for (XMLObject attributeValue : attribute.getAttributeValues()) {
                            Element attributeValueElement = attributeValue.getDOM();
                            String text = attributeValueElement.getTextContent();
                            parameterBean.addAttributeValue(text);
                        }
                    }
                }
            }
        } else if (wrapper.getSaml1() != null) {
            for (org.opensaml.saml.saml1.core.AttributeStatement attributeStatement : wrapper.getSaml1().getAttributeStatements()) {
                for (org.opensaml.saml.saml1.core.Attribute attribute : attributeStatement.getAttributes()) {
                    if ("ActAs".equals(attribute.getAttributeName())) {
                        for (XMLObject attributeValue : attribute.getAttributeValues()) {
                            Element attributeValueElement = attributeValue.getDOM();
                            String text = attributeValueElement.getTextContent();
                            parameterBean.addAttributeValue(text);
                        }
                    }
                }
            }
        }
    }
    return parameterBean;
}
Also used : SAMLTokenPrincipal(org.apache.wss4j.common.principal.SAMLTokenPrincipal) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) XMLObject(org.opensaml.core.xml.XMLObject) AttributeBean(org.apache.wss4j.common.saml.bean.AttributeBean) SAMLTokenPrincipalImpl(org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl)

Example 24 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class SAMLTokenProvider method createToken.

/**
 * 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");
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
Also used : Element(org.w3c.dom.Element) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements)

Example 25 with SamlAssertionWrapper

use of org.apache.wss4j.common.saml.SamlAssertionWrapper in project cxf by apache.

the class SAMLTokenRenewer method renewToken.

/**
 * 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);
    }
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SamlAssertionWrapper(org.apache.wss4j.common.saml.SamlAssertionWrapper) Document(org.w3c.dom.Document) DateTime(org.joda.time.DateTime) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) STSException(org.apache.cxf.ws.security.sts.provider.STSException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) TokenStore(org.apache.cxf.ws.security.tokenstore.TokenStore)

Aggregations

SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)141 Element (org.w3c.dom.Element)68 Document (org.w3c.dom.Document)55 WSSecurityEngineResult (org.apache.wss4j.dom.engine.WSSecurityEngineResult)44 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)40 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)35 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)27 Crypto (org.apache.wss4j.common.crypto.Crypto)26 Response (org.opensaml.saml.saml2.core.Response)23 URL (java.net.URL)22 Bus (org.apache.cxf.Bus)20 SpringBusFactory (org.apache.cxf.bus.spring.SpringBusFactory)19 ArrayList (java.util.ArrayList)18 WebClient (org.apache.cxf.jaxrs.client.WebClient)18 Status (org.opensaml.saml.saml2.core.Status)18 HashMap (java.util.HashMap)16 Test (org.junit.Test)16 Principal (java.security.Principal)15 WSHandlerResult (org.apache.wss4j.dom.handler.WSHandlerResult)14 Response (javax.ws.rs.core.Response)13