Package org.apache.ws.security.message.token

Examples of org.apache.ws.security.message.token.UsernameToken


        sig.addResourceResolver(EnvelopeIdResolver.getInstance());

        X509Certificate[] certs = null;
        KeyInfo info = sig.getKeyInfo();
        byte[] secretKey = null;
        UsernameToken ut = null;
        DerivedKeyToken dkt = null;
        SAMLKeyInfo samlKi = null;
        String customTokenId = null;
        java.security.PublicKey publicKey = null;
       
        if (info != null && info.containsKeyValue()) {
            try {
                publicKey = info.getPublicKey();
            } catch (Exception ex) {
                throw new WSSecurityException(ex.getMessage(), ex);
            }
        } else if (info != null) {
            Node node =
                WSSecurityUtil.getDirectChild(
                    info.getElement(),
                    SecurityTokenReference.SECURITY_TOKEN_REFERENCE,
                    WSConstants.WSSE_NS
                );
            if (node == null) {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
                );
            }
            SecurityTokenReference secRef = new SecurityTokenReference((Element) node);
            int docHash = elem.getOwnerDocument().hashCode();
            //
            // Here we get some information about the document that is being
            // processed, in particular the crypto implementation, and already
            // detected BST that may be used later during dereferencing.
            //
            WSDocInfo wsDocInfo = WSDocInfoStore.lookup(docHash);

            if (secRef.containsReference()) {
                Element token = secRef.getTokenElement(elem.getOwnerDocument(), wsDocInfo, cb);
                //
                // at this point check token type: UsernameToken, Binary, SAML
                // Crypto required only for Binary and SAML
                //
                QName el = new QName(token.getNamespaceURI(), token.getLocalName());
                if (el.equals(WSSecurityEngine.usernameToken)) {
                    String id = token.getAttributeNS(WSConstants.WSU_NS, "Id");
                    UsernameTokenProcessor utProcessor =
                        (UsernameTokenProcessor) wsDocInfo.getProcessor(id);
                    ut = utProcessor.getUt();
                    if (ut.isDerivedKey()) {
                        secretKey = ut.getDerivedKey();
                    } else {
                        secretKey = ut.getSecretKey();
                    }
                } else if (el.equals(WSSecurityEngine.DERIVED_KEY_TOKEN_05_02)
                    || el.equals(WSSecurityEngine.DERIVED_KEY_TOKEN_05_12)) {
                    dkt = new DerivedKeyToken(token);
                    String id = dkt.getID();
                    DerivedKeyTokenProcessor dktProcessor =
                        (DerivedKeyTokenProcessor) wsDocInfo.getProcessor(id);
                    String signatureMethodURI = sig.getSignedInfo().getSignatureMethodURI();
                    int keyLength = (dkt.getLength() > 0) ? dkt.getLength() :
                        WSSecurityUtil.getKeyLength(signatureMethodURI);
                   
                    secretKey = dktProcessor.getKeyBytes(keyLength);
                } else {
                    if (el.equals(WSSecurityEngine.binaryToken)) {
                        // TODO: Use results from BinarySecurityTokenProcessor
                        certs = getCertificatesTokenReference(token, crypto);
                    } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                        if (crypto == null) {
                            throw new WSSecurityException(
                                WSSecurityException.FAILURE, "noSigCryptoFile"
                            );
                        }
                        samlKi = SAMLUtil.getSAMLKeyInfo(token, crypto, cb);
                        certs = samlKi.getCerts();
                        secretKey = samlKi.getSecret();

                    } else if (el.equals(WSSecurityEngine.ENCRYPTED_KEY)){
                        String encryptedKeyID = token.getAttributeNS(null,"Id");                  
                        EncryptedKeyProcessor encryptKeyProcessor =
                            (EncryptedKeyProcessor)wsDocInfo.getProcessor(encryptedKeyID);
                       
                        if (encryptKeyProcessor == null ) {
                            if (crypto == null) {
                                throw new WSSecurityException(
                                    WSSecurityException.FAILURE, "noSigCryptoFile"
                                );
                            }
                            encryptKeyProcessor = new EncryptedKeyProcessor();
                            encryptKeyProcessor.handleEncryptedKey((Element)token, cb, crypto);
                        }
                        secretKey = encryptKeyProcessor.getDecryptedBytes();
                    } else {
                        // Try custom token through callback handler
                        // try to find a custom token
                        String id = secRef.getReference().getURI();
                        if (id.charAt(0) == '#') {
                            id = id.substring(1);
                        }
                        WSPasswordCallback pwcb =
                            new WSPasswordCallback(id, WSPasswordCallback.CUSTOM_TOKEN);
                        try {
                            Callback[] callbacks = new Callback[]{pwcb};
                            cb.handle(callbacks);
                        } catch (Exception e) {
                            throw new WSSecurityException(
                                WSSecurityException.FAILURE,
                                "noPassword",
                                new Object[] {id},
                                e
                            );
                        }
                       
                        secretKey = pwcb.getKey();
                        customTokenId = id;
                        if (secretKey == null) {
                            throw new WSSecurityException(
                                WSSecurityException.INVALID_SECURITY,
                                "unsupportedKeyInfo",
                                new Object[]{el.toString()}
                            );
                        }
                    }
                }
            } else if (secRef.containsX509Data() || secRef.containsX509IssuerSerial()) {
                certs = secRef.getX509IssuerSerial(crypto);
            } else if (secRef.containsKeyIdentifier()) {
                if (secRef.getKeyIdentifierValueType().equals(SecurityTokenReference.ENC_KEY_SHA1_URI)) {
                   
                    String id = secRef.getKeyIdentifierValue();
                    WSPasswordCallback pwcb =
                        new WSPasswordCallback(
                            id,
                            null,
                            SecurityTokenReference.ENC_KEY_SHA1_URI,
                            WSPasswordCallback.ENCRYPTED_KEY_TOKEN
                        );
                    try {
                        Callback[] callbacks = new Callback[]{pwcb};
                        cb.handle(callbacks);
                    } catch (Exception e) {
                        throw new WSSecurityException(
                            WSSecurityException.FAILURE,
                            "noPassword",
                            new Object[] {id},
                            e
                        );
                    }
                    secretKey = pwcb.getKey();
                } else {
                    certs = secRef.getKeyIdentifier(crypto);
                }
            } else {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY,
                    "unsupportedKeyInfo",
                    new Object[]{node.toString()}
                );
            }
        } else {
            if (crypto == null) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noSigCryptoFile");
            }
            if (crypto.getDefaultX509Alias() != null) {
                certs = crypto.getCertificates(crypto.getDefaultX509Alias());
            } else {
                throw new WSSecurityException(
                    WSSecurityException.INVALID_SECURITY, "unsupportedKeyInfo"
                );
            }
        }
        if (tlog.isDebugEnabled()) {
            t1 = System.currentTimeMillis();
        }
        if ((certs == null || certs.length == 0 || certs[0] == null)
            && secretKey == null
            && publicKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
        if (certs != null) {
            try {
                certs[0].checkValidity();
            } catch (CertificateExpiredException e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_CHECK, "invalidCert", null, e
                );
            } catch (CertificateNotYetValidException e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_CHECK, "invalidCert", null, e
                );
            }
        }
        //
        // Delegate verification of a public key to a Callback Handler
        //
        if (publicKey != null) {
            PublicKeyCallback pwcb =
                new PublicKeyCallback(publicKey);
            try {
                Callback[] callbacks = new Callback[]{pwcb};
                cb.handle(callbacks);
                if (!pwcb.isVerified()) {
                    throw new WSSecurityException(
                        WSSecurityException.FAILED_AUTHENTICATION, null, null, null
                    );
                }
            } catch (Exception e) {
                throw new WSSecurityException(
                    WSSecurityException.FAILED_AUTHENTICATION, null, null, e
                );
            }
        }
        try {
            boolean signatureOk = false;
            if (certs != null) {
                signatureOk = sig.checkSignatureValue(certs[0]);
            } else if (publicKey != null) {
                signatureOk = sig.checkSignatureValue(publicKey);
            } else {
                signatureOk = sig.checkSignatureValue(sig.createSecretKey(secretKey));
            }
            if (signatureOk) {
                if (tlog.isDebugEnabled()) {
                    t2 = System.currentTimeMillis();
                    tlog.debug(
                        "Verify: total= " + (t2 - t0) + ", prepare-cert= " + (t1 - t0)
                        + ", verify= " + (t2 - t1)
                    );
                }
                signatureValue[0] = sig.getSignatureValue();
                //
                // Now dig into the Signature element to get the elements that
                // this Signature covers. Build the QName of these Elements and
                // return them to caller
                //
                SignedInfo si = sig.getSignedInfo();
                int numReferences = si.getLength();
                for (int i = 0; i < numReferences; i++) {
                    Reference siRef;
                    try {
                        siRef = si.item(i);
                    } catch (XMLSecurityException e3) {
                        throw new WSSecurityException(
                            WSSecurityException.FAILED_CHECK, null, null, e3
                        );
                    }
                    String uri = siRef.getURI();
                    if (uri != null && !"".equals(uri)) {
                        Element se = WSSecurityUtil.getElementByWsuId(elem.getOwnerDocument(), uri);
                        if (se == null) {
                            se = WSSecurityUtil.getElementByGenId(elem.getOwnerDocument(), uri);
                        }
                        if (se == null) {
                            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
                        }
                        WSDataRef ref = new WSDataRef(uri);
                        ref.setWsuId(uri);
                        ref.setName(new QName(se.getNamespaceURI(), se.getLocalName()));
                        protectedElements.add(ref);
                        returnElements.add(WSSecurityUtil.getIDFromReference(uri));
                    } else {
                       // This is the case where the signed element is identified
                       // by a transform such as XPath filtering
                       // We add the complete reference element to the return
                       // elements
                       returnElements.add(siRef);
                    }
                }
               
                if (certs != null) {
                    returnCert[0] = certs[0];
                    return certs[0].getSubjectDN();
                } else if (publicKey != null) {
                    return new PublicKeyPrincipal(publicKey);
                } else if (ut != null) {
                    WSUsernameTokenPrincipal principal =
                        new WSUsernameTokenPrincipal(ut.getName(), ut.isHashed());
                    principal.setNonce(ut.getNonce());
                    principal.setPassword(ut.getPassword());
                    principal.setCreatedTime(ut.getCreated());
                    return principal;
                } else if (dkt != null) {
                    WSDerivedKeyTokenPrincipal principal = new WSDerivedKeyTokenPrincipal(dkt.getID());
                    principal.setNonce(dkt.getNonce());
                    principal.setLabel(dkt.getLabel());
View Full Code Here


     * constructed.
     *
     * @param doc The SOAP envelope as W3C document
     */
    public void prepare(Document doc) {
        ut = new UsernameToken(wssConfig.isPrecisionInMilliSeconds(), doc, passwordType);
        ut.setName(user);
        if (useDerivedKey) {
            saltValue = ut.addSalt(doc, saltValue, useMac);
            ut.addIteration(doc, iteration);
        } else {
View Full Code Here

        org.apache.cxf.ws.security.policy.model.UsernameToken usernameTokenPolicy,
        AssertionInfo ai,
        List<WSSecurityEngineResult> utResults
    ) {
        for (WSSecurityEngineResult result : utResults) {
            UsernameToken usernameToken =
                (UsernameToken)result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN);
            if (usernameTokenPolicy.isHashPassword() != usernameToken.isHashed()) {
                ai.setNotAsserted("Password hashing policy not enforced");
                return false;
            }
            if (usernameTokenPolicy.isNoPassword() && (usernameToken.getPassword() != null)) {
                ai.setNotAsserted("Username Token NoPassword policy not enforced");
                return false;
            } else if (!usernameTokenPolicy.isNoPassword() && (usernameToken.getPassword() == null)
                && isNonEndorsingSupportingToken(usernameTokenPolicy)) {
                ai.setNotAsserted("Username Token No Password supplied");
                return false;
            }
           
            if (usernameTokenPolicy.isRequireCreated()
                && (usernameToken.getCreated() == null || usernameToken.isHashed())) {
                ai.setNotAsserted("Username Token Created policy not enforced");
                return false;
            }
            if (usernameTokenPolicy.isRequireNonce()
                && (usernameToken.getNonce() == null || usernameToken.isHashed())) {
                ai.setNotAsserted("Username Token Nonce policy not enforced");
                return false;
            }
        }
        return true;
View Full Code Here

     * constructed.
     *
     * @param doc The SOAP envelope as W3C document
     */
    public void prepare(Document doc) {
        ut = new UsernameToken(wssConfig.isPrecisionInMilliSeconds(), doc, passwordType);
        ut.setName(user);
        if (useDerivedKey) {
            saltValue = ut.addSalt(doc, saltValue, useMac);
            ut.addIteration(doc, iteration);
        } else {
View Full Code Here

            throw new WSSecurityException(WSSecurityException.FAILURE, "noCallback");
        }
        //
        // Parse the UsernameToken element
        //
        ut = new UsernameToken(token, allowNamespaceQualifiedPasswordTypes);
        String user = ut.getName();
        String password = ut.getPassword();
        String nonce = ut.getNonce();
        String createdTime = ut.getCreated();
        String pwType = ut.getPasswordType();
View Full Code Here

    public void testUsernameTokenUnit() throws Exception {
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
       
        UsernameToken usernameToken = new UsernameToken(true, doc, null);
        usernameToken.setName("bob");
       
        byte[] salt = usernameToken.addSalt(doc, null, false);
        assertTrue(salt.length == 16);
        assertTrue(salt[15] == 0x02);
        byte[] utSalt = usernameToken.getSalt();
        assertTrue(salt.length == utSalt.length);
        for (int i = 0; i < salt.length; i++) {
            assertTrue(salt[i] == utSalt[i]);
        }
       
        usernameToken.addIteration(doc, 500);
        assertTrue(usernameToken.getIteration() == 500);
       
        WSSecurityUtil.prependChildElement(
            secHeader.getSecurityHeader(), usernameToken.getElement()
        );
       
        String outputString =
            org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        assertTrue(outputString.indexOf("wsse:Username") != -1);
View Full Code Here

        }
       
        String user = null;
        String password = null;
       
        UsernameToken usernameToken = credential.getUsernametoken();
       
        user = usernameToken.getName();
        String pwType = usernameToken.getPasswordType();
        if (log.isDebugEnabled()) {
            log.debug("UsernameToken user " + usernameToken.getName());
            log.debug("UsernameToken password type " + pwType);
        }
       
        if (usernameToken.isHashed()) {
            log.warn("Authentication failed as hashed username token not supported");
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);
        }
       
        password = usernameToken.getPassword();
       
        if (!WSConstants.PASSWORD_TEXT.equals(pwType)) {
            log.warn("Password type " + pwType + " not supported");
            throw new WSSecurityException(WSSecurityException.FAILED_AUTHENTICATION);         
        }
View Full Code Here

        int action = ((Integer)result.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
        if (WSConstants.UT_NOPASSWORD == action || WSConstants.UT == action) {
            if (bspCompliant) {
                BSPEnforcer.checkUsernameTokenBSPCompliance(secRef);
            }
            UsernameToken usernameToken =
                (UsernameToken)result.get(WSSecurityEngineResult.TAG_USERNAME_TOKEN);
            usernameToken.setRawPassword(data);
            secretKey = usernameToken.getDerivedKey();
        } else if (WSConstants.ENCR == action) {
            if (bspCompliant) {
                BSPEnforcer.checkEncryptedKeyBSPCompliance(secRef);
            }
            secretKey = (byte[])result.get(WSSecurityEngineResult.TAG_SECRET);
View Full Code Here

            }
        }
       
        Validator validator = data.getValidator(WSSecurityEngine.USERNAME_TOKEN);
        Credential credential = handleUsernameToken(elem, validator, data);
        UsernameToken token = credential.getUsernametoken();
       
        int action = WSConstants.UT;
        if (token.getPassword() == null) {
            action = WSConstants.UT_NOPASSWORD;
        }
        WSSecurityEngineResult result = new WSSecurityEngineResult(action, token);
        result.put(WSSecurityEngineResult.TAG_ID, token.getID());
       
        if (validator != null) {
            result.put(WSSecurityEngineResult.TAG_VALIDATED_TOKEN, Boolean.TRUE);
            if (credential.getTransformedToken() != null) {
                result.put(
                    WSSecurityEngineResult.TAG_TRANSFORMED_TOKEN, credential.getTransformedToken()
                );
                SAMLTokenPrincipal samlPrincipal =
                    new SAMLTokenPrincipal(credential.getTransformedToken());
                result.put(WSSecurityEngineResult.TAG_PRINCIPAL, samlPrincipal);
            } else {
                WSUsernameTokenPrincipal principal =
                    new WSUsernameTokenPrincipal(token.getName(), token.isHashed());
                principal.setNonce(token.getNonce());
                principal.setPassword(token.getPassword());
                principal.setCreatedTime(token.getCreated());
                principal.setPasswordType(token.getPasswordType());
                result.put(WSSecurityEngineResult.TAG_PRINCIPAL, principal);
            }
        }
       
        wsDocInfo.addTokenElement(elem);
View Full Code Here

        }
       
        //
        // Parse and validate the UsernameToken element
        //
        UsernameToken ut =
            new UsernameToken(token, allowNamespaceQualifiedPasswordTypes, bspCompliant);
        Credential credential = new Credential();
        credential.setUsernametoken(ut);
        if (validator != null) {
            return validator.validate(credential, data);
        }
View Full Code Here

TOP

Related Classes of org.apache.ws.security.message.token.UsernameToken

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.