Package org.apache.cxf.sts.request

Examples of org.apache.cxf.sts.request.ReceivedToken


            createSAMLAssertionWithRoles(WSConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey",
                                         callbackHandler, "manager");
        Document doc = samlToken.getOwnerDocument();
        samlToken = (Element)doc.appendChild(samlToken);
       
        ReceivedToken validateTarget = new ReceivedToken(samlToken);
        tokenRequirements.setValidateTarget(validateTarget);
        validatorParameters.setToken(validateTarget);
       
        // Disable caching
        validatorParameters.setTokenStore(null);
View Full Code Here


            createSAMLAssertionWithRoles(WSConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey",
                                         callbackHandler, "employee");
        Document doc = samlToken.getOwnerDocument();
        samlToken = (Element)doc.appendChild(samlToken);
       
        ReceivedToken validateTarget = new ReceivedToken(samlToken);
        tokenRequirements.setValidateTarget(validateTarget);
        validatorParameters.setToken(validateTarget);
       
        assertTrue(samlTokenValidator.canHandleToken(validateTarget));
       
View Full Code Here

        Element samlToken =
            createSAMLAssertion(WSConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey", callbackHandler);
        Document doc = samlToken.getOwnerDocument();
        samlToken = (Element)doc.appendChild(samlToken);
       
        ReceivedToken validateTarget = new ReceivedToken(samlToken);
        tokenRequirements.setValidateTarget(validateTarget);
        validatorParameters.setToken(validateTarget);
       
        assertTrue(samlTokenValidator.canHandleToken(validateTarget));
       
        TokenValidatorResponse validatorResponse =
            samlTokenValidator.validateToken(validatorParameters);
        assertTrue(validatorResponse != null);
        assertTrue(validatorResponse.getToken() != null);
        assertTrue(validatorResponse.getToken().getState() == STATE.VALID);
       
        // Replace "alice" with "bob".
        Element nameID =
            (Element)samlToken.getElementsByTagNameNS(WSConstants.SAML2_NS, "NameID").item(0);
        nameID.setTextContent("bob");
       
        // Now validate again
        validateTarget = new ReceivedToken(samlToken);
        tokenRequirements.setValidateTarget(validateTarget);
        validatorParameters.setToken(validateTarget);
       
        assertTrue(samlTokenValidator.canHandleToken(validateTarget));
       
View Full Code Here

            ProcessedClaim claim = claimIterator.next();
            AttributeBean attributeBean = createAttributeFromClaim(claim, tokenType);
            attributeList.add(attributeBean);
        }
       
        ReceivedToken onBehalfOf = tokenRequirements.getOnBehalfOf();
        ReceivedToken actAs = tokenRequirements.getActAs();
        try {
            if (onBehalfOf != null) {
                AttributeBean parameterBean =
                    handleAdditionalParameters(false, onBehalfOf.getToken(), tokenType);
                if (!parameterBean.getAttributeValues().isEmpty()) {
                    attributeList.add(parameterBean);
                }
            }
            if (actAs != null) {
                AttributeBean parameterBean =
                    handleAdditionalParameters(true, actAs.getToken(), tokenType);
                if (!parameterBean.getAttributeValues().isEmpty()) {
                    attributeList.add(parameterBean);
                }
            }
        } catch (WSSecurityException ex) {
View Full Code Here

        String tokenType = tokenRequirements.getTokenType();
        String keyType = keyRequirements.getKeyType();
        String confirmationMethod = getSubjectConfirmationMethod(tokenType, keyType);
       
        Principal principal = null;
        ReceivedToken receivedToken = null;
        //[TODO] ActAs support
        //TokenValidator in IssueOperation has validated the ReceivedToken
        //if validation was successful, the principal was set in ReceivedToken
        if (providerParameters.getTokenRequirements().getOnBehalfOf() != null) {
            receivedToken = providerParameters.getTokenRequirements().getOnBehalfOf();   
            if (receivedToken.getState().equals(STATE.VALID)) {
                principal = receivedToken.getPrincipal();
            }
        } else if (providerParameters.getTokenRequirements().getValidateTarget() != null) {
            receivedToken = providerParameters.getTokenRequirements().getValidateTarget();
            if (receivedToken.getState().equals(STATE.VALID)) {
                principal = receivedToken.getPrincipal();
            }
        } else {
            principal = providerParameters.getPrincipal();
        }
       
View Full Code Here

    /**
     * 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) {
View Full Code Here

        requestData.setWssConfig(WSSConfig.getNewInstance());
        requestData.setCallbackHandler(callbackHandler);
        requestData.setMsgContext(tokenParameters.getWebServiceContext().getMessageContext());

        TokenValidatorResponse response = new TokenValidatorResponse();
        ReceivedToken validateTarget = tokenParameters.getToken();
        validateTarget.setState(STATE.INVALID);
        response.setToken(validateTarget);
       
        if (!validateTarget.isBinarySecurityToken()) {
            return response;
        }

        BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType)validateTarget.getToken();

        // Test the encoding type
        String encodingType = binarySecurityType.getEncodingType();
        if (!BASE64_ENCODING.equals(encodingType)) {
            LOG.fine("Bad encoding type attribute specified: " + encodingType);
            return response;
        }

        //
        // Turn the received JAXB object into a DOM element
        //
        Document doc = DOMUtils.createDocument();
        BinarySecurity binarySecurity = new X509Security(doc);
        binarySecurity.setEncodingType(encodingType);
        binarySecurity.setValueType(binarySecurityType.getValueType());
        String data = binarySecurityType.getValue();
        ((Text)binarySecurity.getElement().getFirstChild()).setData(data);

        //
        // Validate the token
        //
        try {
            Credential credential = new Credential();
            credential.setBinarySecurityToken(binarySecurity);
            if (sigCrypto != null) {
                X509Certificate cert = ((X509Security)binarySecurity).getX509Certificate(sigCrypto);
                credential.setCertificates(new X509Certificate[]{cert});
            }

            Credential returnedCredential = validator.validate(credential, requestData);
            response.setPrincipal(returnedCredential.getCertificates()[0].getSubjectX500Principal());
            validateTarget.setState(STATE.VALID);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        }
        return response;
    }
View Full Code Here

        requestData.setWssConfig(wssConfig);
        requestData.setCallbackHandler(callbackHandler);
        requestData.setMsgContext(tokenParameters.getWebServiceContext().getMessageContext());
       
        TokenValidatorResponse response = new TokenValidatorResponse();
        ReceivedToken validateTarget = tokenParameters.getToken();
        validateTarget.setState(STATE.INVALID);
        response.setToken(validateTarget);

        if (!validateTarget.isUsernameToken()) {
            return response;
        }
       
        //
        // Turn the JAXB UsernameTokenType into a DOM Element for validation
        //
        UsernameTokenType usernameTokenType = (UsernameTokenType)validateTarget.getToken();
       
        // Marshall the received JAXB object into a DOM Element
        Element usernameTokenElement = null;
        try {
            Set<Class<?>> classes = new HashSet<Class<?>>();
            classes.add(ObjectFactory.class);
            classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
                   
            CachedContextAndSchemas cache =
                JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
            JAXBContext jaxbContext = cache.getContext();
           
            Marshaller marshaller = jaxbContext.createMarshaller();
            Document doc = DOMUtils.createDocument();
            Element rootElement = doc.createElement("root-element");
            JAXBElement<UsernameTokenType> tokenType =
                new JAXBElement<UsernameTokenType>(
                    QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType
                );
            marshaller.marshal(tokenType, rootElement);
            usernameTokenElement = (Element)rootElement.getFirstChild();
        } catch (JAXBException ex) {
            LOG.log(Level.WARNING, "", ex);
            return response;
        }
       
        //
        // Validate the token
        //
        try {
            boolean allowNamespaceQualifiedPasswordTypes =
                wssConfig.getAllowNamespaceQualifiedPasswordTypes();
            UsernameToken ut =
                new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes,
                                  new BSPEnforcer());
            // The parsed principal is set independent whether validation is successful or not
            response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
            if (ut.getPassword() == null) {
                return response;
            }
           
            // See if the UsernameToken is stored in the cache
            int hash = ut.hashCode();
            SecurityToken secToken = null;
            if (tokenParameters.getTokenStore() != null) {
                secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
                if (secToken != null && (secToken.getTokenHash() != hash || secToken.isExpired())) {
                    secToken = null;
                }
            }
           
            if (secToken == null) {
                Credential credential = new Credential();
                credential.setUsernametoken(ut);
                validator.validate(credential, requestData);
            }
           
            Principal principal =
                createPrincipal(
                    ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated()
                );
           
            // Get the realm of the UsernameToken
            String tokenRealm = null;
            if (usernameTokenRealmCodec != null) {
                tokenRealm = usernameTokenRealmCodec.getRealmFromToken(ut);
                // verify the realm against the cached token
                if (secToken != null) {
                    Properties props = secToken.getProperties();
                    if (props != null) {
                        String cachedRealm = props.getProperty(STSConstants.TOKEN_REALM);
                        if (!tokenRealm.equals(cachedRealm)) {
                            return response;
                        }
                    }
                }
            }
           
            // Store the successfully validated token in the cache
            if (tokenParameters.getTokenStore() != null && secToken == null) {
                secToken = new SecurityToken(ut.getID());
                secToken.setToken(ut.getElement());
                int hashCode = ut.hashCode();
                String identifier = Integer.toString(hashCode);
                secToken.setTokenHash(hashCode);
                tokenParameters.getTokenStore().add(identifier, secToken);
            }
           
            response.setPrincipal(principal);
            response.setTokenRealm(tokenRealm);
            validateTarget.setState(STATE.VALID);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        } catch (Base64DecodingException ex) {
            LOG.log(Level.WARNING, "", ex);
        }
View Full Code Here

        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        Crypto sigCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
       
        TokenValidatorResponse response = new TokenValidatorResponse();
        ReceivedToken validateTarget = tokenParameters.getToken();
        validateTarget.setState(STATE.INVALID);
        response.setToken(validateTarget);
       
        if (!validateTarget.isDOMElement()) {
            return response;
        }
       
        try {
            Element validateTargetElement = (Element)validateTarget.getToken();
            SamlAssertionWrapper assertion = new SamlAssertionWrapper(validateTargetElement);
           
            SAMLTokenPrincipal samlPrincipal = new SAMLTokenPrincipalImpl(assertion);
            response.setPrincipal(samlPrincipal);
           
            if (!assertion.isSigned()) {
                LOG.log(Level.WARNING, "The received assertion is not signed, and therefore not trusted");
                return response;
            }

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

            WSDocInfo docInfo = new WSDocInfo(validateTargetElement.getOwnerDocument());

            // Verify the signature
            Signature sig = assertion.getSignature();
            KeyInfo keyInfo = sig.getKeyInfo();
            SAMLKeyInfo samlKeyInfo =
                SAMLUtil.getCredentialFromKeyInfo(
                    keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData, docInfo), sigCrypto
                );
            assertion.verifySignature(samlKeyInfo);
               
            SecurityToken secToken = null;
            byte[] signatureValue = assertion.getSignatureValue();
            if (tokenParameters.getTokenStore() != null && signatureValue != null
                && signatureValue.length > 0) {
                int hash = Arrays.hashCode(signatureValue);
                secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
                if (secToken != null && secToken.getTokenHash() != hash) {
                    secToken = null;
                }
            }
            if (secToken != null && secToken.isExpired()) {
                LOG.fine("Token: " + secToken.getId() + " is in the cache but expired - revalidating");
                secToken = null;
            }
           
            if (secToken == null) {
                // Validate the assertion against schemas/profiles
                validateAssertion(assertion);

                // Now verify trust on the signature
                Credential trustCredential = new Credential();
                trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
                trustCredential.setCertificates(samlKeyInfo.getCerts());
   
                trustCredential = validator.validate(trustCredential, requestData);

                // Finally check that subject DN of the signing certificate matches a known constraint
                X509Certificate cert = null;
                if (trustCredential.getCertificates() != null) {
                    cert = trustCredential.getCertificates()[0];
                }
               
                if (!certConstraints.matches(cert)) {
                    return response;
                }
            }
           
            // Parse roles from the validated token
            if (samlRoleParser != null) {
                Set<Principal> roles =
                    samlRoleParser.parseRolesFromAssertion(samlPrincipal, null, assertion);
                response.setRoles(roles);
            }
          
            // Get the realm of the SAML token
            String tokenRealm = null;
            if (samlRealmCodec != null) {
                tokenRealm = samlRealmCodec.getRealmFromToken(assertion);
                // verify the realm against the cached token
                if (secToken != null) {
                    Properties props = secToken.getProperties();
                    if (props != null) {
                        String cachedRealm = props.getProperty(STSConstants.TOKEN_REALM);
                        if (cachedRealm != null && !tokenRealm.equals(cachedRealm)) {
                            return response;
                        }
                    }
                }
            }
            response.setTokenRealm(tokenRealm);
           
            if (!validateConditions(assertion, validateTarget)) {
                return response;
            }
           
            // Store the successfully validated token in the cache
            if (secToken == null) {
                storeTokenInCache(
                    tokenParameters.getTokenStore(), assertion, tokenParameters.getPrincipal(), tokenRealm
                );
            }
           
            // Add the SamlAssertionWrapper to the properties, as the claims are required to be transformed
            Map<String, Object> addProps = new HashMap<String, Object>();
            addProps.put(SamlAssertionWrapper.class.getName(), assertion);
            response.setAdditionalProperties(addProps);
           
            validateTarget.setState(STATE.VALID);
        } catch (WSSecurityException ex) {
            LOG.log(Level.WARNING, "", ex);
        }

        return response;
View Full Code Here

            response.setValid(false);
            return response;
        }
       
        TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
        ReceivedToken validateTarget = tokenRequirements.getValidateTarget();

        TokenValidatorResponse response = new TokenValidatorResponse();
        response.setValid(false);
       
        if (validateTarget != null && validateTarget.isDOMElement()) {
            try {
                Element validateTargetElement = (Element)validateTarget.getToken();
                SecurityContextToken sct = new SecurityContextToken(validateTargetElement);
                String identifier = sct.getIdentifier();
                SecurityToken token = tokenParameters.getTokenStore().getToken(identifier);
                if (token == null) {
                    LOG.fine("Identifier: " + identifier + " is not found in the cache");
View Full Code Here

TOP

Related Classes of org.apache.cxf.sts.request.ReceivedToken

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.