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

The following examples show how to use org.apache.wss4j.common.saml.SamlAssertionWrapper#getSaml1() . 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: ClaimsValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    boolean valid = false;
    if (assertion.getSaml1() != null) {
        valid = handleSAML1Assertion(assertion.getSaml1());
    } else if (assertion.getSaml2() != null) {
        valid = handleSAML2Assertion(assertion.getSaml2());
    }

    if (valid) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example 2
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void createNewConditions(SamlAssertionWrapper assertion, TokenRenewerParameters tokenParameters) {
    ConditionsBean conditions =
        conditionsProvider.getConditions(convertToProviderParameters(tokenParameters));

    if (assertion.getSaml1() != null) {
        org.opensaml.saml.saml1.core.Assertion saml1Assertion = assertion.getSaml1();
        saml1Assertion.setIssueInstant(new DateTime());

        org.opensaml.saml.saml1.core.Conditions saml1Conditions =
            SAML1ComponentBuilder.createSamlv1Conditions(conditions);

        saml1Assertion.setConditions(saml1Conditions);
    } else {
        org.opensaml.saml.saml2.core.Assertion saml2Assertion = assertion.getSaml2();
        saml2Assertion.setIssueInstant(new DateTime());

        org.opensaml.saml.saml2.core.Conditions saml2Conditions =
            SAML2ComponentBuilder.createConditions(conditions);

        saml2Assertion.setConditions(saml2Conditions);
    }
}
 
Example 3
Source File: IssuedTokenPolicyValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SecurityToken createSecurityToken(
    SamlAssertionWrapper assertionWrapper
) {
    SecurityToken token = new SecurityToken(assertionWrapper.getId());

    SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
    if (subjectKeyInfo != null) {
        token.setSecret(subjectKeyInfo.getSecret());
        X509Certificate[] certs = subjectKeyInfo.getCerts();
        if (certs != null && certs.length > 0) {
            token.setX509Certificate(certs[0], null);
        }
        if (subjectKeyInfo.getPublicKey() != null) {
            token.setKey(subjectKeyInfo.getPublicKey());
        }
    }
    if (assertionWrapper.getSaml1() != null) {
        token.setTokenType(WSS4JConstants.WSS_SAML_TOKEN_TYPE);
    } else if (assertionWrapper.getSaml2() != null) {
        token.setTokenType(WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
    }
    token.setToken(assertionWrapper.getElement());

    return token;
}
 
Example 4
Source File: DefaultClaimsPolicyValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean findClaimInAssertion(SamlAssertionWrapper assertion, URI claimURI) {
    if (assertion.getSaml1() != null) {
        return findClaimInAssertion(assertion.getSaml1(), claimURI);
    } else if (assertion.getSaml2() != null) {
        return findClaimInAssertion(assertion.getSaml2(), claimURI);
    }
    return false;
}
 
Example 5
Source File: CustomSamlValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential returnedCredential = super.validate(credential, data);

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

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

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

    return returnedCredential;
}
 
Example 6
Source File: StaxClaimsValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends SamlSecurityToken & InboundSecurityToken> T validate(
                                             final SamlAssertionWrapper samlAssertionWrapper,
                                             final InboundSecurityToken subjectSecurityToken,
                                             final TokenContext tokenContext
) throws WSSecurityException {
    // Check conditions
    checkConditions(samlAssertionWrapper);

    // Check OneTimeUse Condition
    checkOneTimeUse(samlAssertionWrapper,
                    tokenContext.getWssSecurityProperties().getSamlOneTimeUseReplayCache());

    // Validate the assertion against schemas/profiles
    validateAssertion(samlAssertionWrapper);

    // Now check Claims
    boolean valid = false;
    if (samlAssertionWrapper.getSaml1() != null) {
        valid = handleSAML1Assertion(samlAssertionWrapper.getSaml1());
    } else if (samlAssertionWrapper.getSaml2() != null) {
        valid = handleSAML2Assertion(samlAssertionWrapper.getSaml2());
    }

    if (!valid) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Crypto sigVerCrypto = null;
    if (samlAssertionWrapper.isSigned()) {
        sigVerCrypto = tokenContext.getWssSecurityProperties().getSignatureVerificationCrypto();
    }
    SamlSecurityTokenImpl securityToken = new SamlSecurityTokenImpl(
            samlAssertionWrapper, subjectSecurityToken,
            tokenContext.getWsSecurityContext(),
            sigVerCrypto,
            WSSecurityTokenConstants.KeyIdentifier_NoKeyInfo,
            tokenContext.getWssSecurityProperties());

    securityToken.setElementPath(tokenContext.getElementPath());
    securityToken.setXMLSecEvent(tokenContext.getFirstXMLSecEvent());

    return (T)securityToken;
}
 
Example 7
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 8
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void validateAssertion(
    SamlAssertionWrapper assertion,
    ReceivedToken tokenToRenew,
    SecurityToken token,
    TokenRenewerParameters tokenParameters
) throws WSSecurityException {
    // Check the cached renewal properties
    Map<String, Object> props = token.getProperties();
    if (props == null) {
        LOG.log(Level.WARNING, "Error in getting properties from cached token");
        throw new STSException(
            "Error in getting properties from cached token", STSException.REQUEST_FAILED
        );
    }
    String isAllowRenewal = (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW);
    String isAllowRenewalAfterExpiry =
        (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY);

    if (isAllowRenewal == null || !Boolean.valueOf(isAllowRenewal)) {
        LOG.log(Level.WARNING, "The token is not allowed to be renewed");
        throw new STSException("The token is not allowed to be renewed", STSException.REQUEST_FAILED);
    }

    // Check to see whether the token has expired greater than the configured max expiry time
    if (tokenToRenew.getState() == STATE.EXPIRED) {
        if (!allowRenewalAfterExpiry || isAllowRenewalAfterExpiry == null
            || !Boolean.valueOf(isAllowRenewalAfterExpiry)) {
            LOG.log(Level.WARNING, "Renewal after expiry is not allowed");
            throw new STSException(
                "Renewal after expiry is not allowed", STSException.REQUEST_FAILED
            );
        }
        DateTime expiryDate = getExpiryDate(assertion);
        DateTime currentDate = new DateTime();
        if ((currentDate.getMillis() - expiryDate.getMillis()) > (maxExpiry * 1000L)) {
            LOG.log(Level.WARNING, "The token expired too long ago to be renewed");
            throw new STSException(
                "The token expired too long ago to be renewed", STSException.REQUEST_FAILED
            );
        }
    }

    // Verify Proof of Possession
    ProofOfPossessionValidator popValidator = new ProofOfPossessionValidator();
    if (verifyProofOfPossession) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        Crypto sigCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);

        WSDocInfo docInfo = new WSDocInfo(((Element)tokenToRenew.getToken()).getOwnerDocument());
        requestData.setWsDocInfo(docInfo);
        // Parse the HOK subject if it exists

        assertion.parseSubject(
            new WSSSAMLKeyInfoProcessor(requestData), sigCrypto, callbackHandler
        );

        SAMLKeyInfo keyInfo = assertion.getSubjectKeyInfo();
        if (keyInfo == null) {
            keyInfo = new SAMLKeyInfo((byte[])null);
        }
        if (!popValidator.checkProofOfPossession(tokenParameters, keyInfo)) {
            throw new STSException(
                "Failed to verify the proof of possession of the key associated with the "
                + "saml token. No matching key found in the request.",
                STSException.INVALID_REQUEST
            );
        }
    }

    // Check the AppliesTo address
    String appliesToAddress = tokenParameters.getAppliesToAddress();
    if (appliesToAddress != null) {
        if (assertion.getSaml1() != null) {
            List<AudienceRestrictionCondition> restrConditions =
                assertion.getSaml1().getConditions().getAudienceRestrictionConditions();
            if (!matchSaml1AudienceRestriction(appliesToAddress, restrConditions)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        } else {
            List<AudienceRestriction> audienceRestrs =
                assertion.getSaml2().getConditions().getAudienceRestrictions();
            if (!matchSaml2AudienceRestriction(appliesToAddress, audienceRestrs)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        }
    }

}
 
Example 9
Source File: CustomStaxSamlValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends SamlSecurityToken & InboundSecurityToken> T validate(
    final SamlAssertionWrapper samlAssertionWrapper,
    final InboundSecurityToken subjectSecurityToken,
    final TokenContext tokenContext
) throws WSSecurityException {
    //jdk 1.6 compiler bug? http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954
    //type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with
    // upper bounds org.apache.wss4j.stax.securityToken.SamlSecurityToken,
    // org.apache.wss4j.stax.securityToken.SamlSecurityToken,
    // org.apache.xml.security.stax.ext.securityToken.InboundSecurityToken
    //works fine on jdk 1.7
    final SamlSecurityToken token =
        super.</*fake @see above*/SamlSecurityTokenImpl>
                    validate(samlAssertionWrapper, subjectSecurityToken, tokenContext);

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

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

    String confirmationMethod = samlAssertionWrapper.getConfirmationMethods().get(0);
    if (confirmationMethod == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    if (requireSenderVouches && !OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    } else if (!requireSenderVouches
        && !OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    return (T)token;
}
 
Example 10
Source File: SAMLProtocolResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate an internal Assertion
 */
private void validateAssertion(
    SamlAssertionWrapper assertion,
    Crypto sigCrypto,
    CallbackHandler callbackHandler,
    Document doc,
    boolean signedResponse
) throws WSSecurityException {
    Credential credential = new Credential();
    credential.setSamlAssertion(assertion);

    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    requestData.setWssConfig(wssConfig);
    requestData.setCallbackHandler(callbackHandler);

    if (assertion.isSigned()) {
        if (assertion.getSaml1() != null) {
            assertion.getSaml1().getDOM().setIdAttributeNS(null, "AssertionID", true);
        } else {
            assertion.getSaml2().getDOM().setIdAttributeNS(null, "ID", true);
        }

        // Verify the signature
        try {
            Signature sig = assertion.getSignature();
            WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
            requestData.setWsDocInfo(docInfo);

            SAMLKeyInfo samlKeyInfo = null;

            KeyInfo keyInfo = sig.getKeyInfo();
            if (keyInfo != null) {
                samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData), sigCrypto
                );
            } else if (!keyInfoMustBeAvailable) {
                samlKeyInfo = createKeyInfoFromDefaultAlias(sigCrypto);
            }

            if (samlKeyInfo == null) {
                LOG.warning("No KeyInfo supplied in the SAMLResponse assertion signature");
                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
            }

            assertion.verifySignature(samlKeyInfo);

            assertion.parseSubject(
                new WSSSAMLKeyInfoProcessor(requestData),
                requestData.getSigVerCrypto(),
                requestData.getCallbackHandler()
            );
        } catch (WSSecurityException e) {
            LOG.log(Level.FINE, "Assertion failed signature validation", e);
            throw e;
        }
    }

    // Validate the Assertion & verify trust in the signature
    try {
        SamlSSOAssertionValidator assertionValidator = new SamlSSOAssertionValidator(signedResponse);
        assertionValidator.validate(credential, requestData);
    } catch (WSSecurityException ex) {
        LOG.log(Level.FINE, "Assertion validation failed: " + ex.getMessage(), ex);
        throw ex;
    }
}