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;

        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();
            /*
                * Her we get some information about the document that is being
                * processed, in partucular 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);
                /*
                     * 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)) {
                    ut = new UsernameToken(token);
                    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 (crypto == null) {
                        throw new WSSecurityException(WSSecurityException.FAILURE,
                                "noSigCryptoFile");
                    }
                    if (el.equals(WSSecurityEngine.binaryToken)) {
                        certs = getCertificatesTokenReference((Element) token,
                                crypto);
                    } else if (el.equals(WSSecurityEngine.SAML_TOKEN)) {
                        certs = SAMLUtil.getCertificatesFromSAML((Element) token);
                    } else {
                        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()) {
                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) {
            throw new WSSecurityException(WSSecurityException.FAILED_CHECK);
        }
        if (certs != null) {
            try {
                certs[0].checkValidity();
            } catch (CertificateExpiredException e) {
                throw new WSSecurityException(WSSecurityException.FAILED_CHECK,
                        "invalidCert");
            } catch (CertificateNotYetValidException e) {
                throw new WSSecurityException(WSSecurityException.FAILED_CHECK,
                        "invalidCert");
            }
        }
        try {
            boolean signatureOk = false;
            if (certs != null) {
                signatureOk = sig.checkSignatureValue(certs[0]);
            } 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();
                Vector qvec = new Vector(numReferences);
                for (int i = 0; i < numReferences; i++) {
                    Reference siRef;
                    try {
                        siRef = si.item(i);
                    } catch (XMLSecurityException e3) {
                        throw new WSSecurityException(
                                WSSecurityException.FAILED_CHECK);
                    }
                    String uri = siRef.getURI();
                    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);
                    }
                    returnElements.add(WSSecurityUtil.getIDfromReference(uri));                   
                }
               
                if (certs != null) {
                    returnCert[0] = certs[0];
                    return certs[0].getSubjectDN();
                } 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


        //
        try {
            boolean allowNamespaceQualifiedPasswordTypes =
                wssConfig.getAllowNamespaceQualifiedPasswordTypes();
            boolean bspCompliant = wssConfig.isWsiBSPCompliant();
            UsernameToken ut =
                new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, bspCompliant);
            // The parsed principal is set independent whether validation is successful or not
            response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
            if (ut.getPassword() == null) {
                return response;
            }
            if (secToken == null || (secToken.getAssociatedHash() != ut.hashCode())) {
                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) {
View Full Code Here

        private WSUsernameTokenPrincipal handleUsernameToken(
            Element token, CallbackHandler cb) throws WSSecurityException {
            //
            // Parse the UsernameToken element
            //
            ut = new UsernameToken(token, false);
            String user = ut.getName();
            String password = ut.getPassword();
            String nonce = ut.getNonce();
            String createdTime = ut.getCreated();
            String pwType = ut.getPasswordType();
View Full Code Here

        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);       
        builder.build(doc, secHeader);
       
        try {
            new UsernameToken(doc.getDocumentElement());
        } catch (WSSecurityException ex) {
            assertTrue(ex.getErrorCode() == 4);
            assertTrue(ex.getMessage().startsWith(
                "An invalid security token was provided"));
            QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurityToken");
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

        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);       
        builder.build(doc, secHeader);
       
        try {
            new UsernameToken(doc.getDocumentElement());
        } catch (WSSecurityException ex) {
            assertTrue(ex.getErrorCode() == 4);
            assertTrue(ex.getMessage().startsWith(
                "An invalid security token was provided"));
            QName faultCode = new QName(WSConstants.WSSE_NS, "InvalidSecurityToken");
View Full Code Here

    public void testUsernameTokenUnit() throws Exception {
        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        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

    public void testNoSaltEncryption() throws Exception {
        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
       
        UsernameToken usernameToken = new UsernameToken(true, doc, null);
        usernameToken.setName("bob");
        WSSConfig config = WSSConfig.getNewInstance();
        usernameToken.setID(config.getIdAllocator().createId("UsernameToken-", usernameToken));
       
        byte[] salt = UsernameToken.generateSalt(false);
        usernameToken.addIteration(doc, 1000);
       
        byte[] derivedKey = UsernameToken.generateDerivedKey("security", salt, 1000);
       
        //
        // Derived key encryption
        //
        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
        encrBuilder.setExternalKey(derivedKey, usernameToken.getID());
        encrBuilder.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        Document encryptedDoc = encrBuilder.build(doc, secHeader);
       
        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

    public void testNoIterationEncryption() throws Exception {
        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
       
        UsernameToken usernameToken = new UsernameToken(true, doc, null);
        usernameToken.setName("bob");
        WSSConfig config = WSSConfig.getNewInstance();
        usernameToken.setID(config.getIdAllocator().createId("UsernameToken-", usernameToken));
       
        byte[] salt = usernameToken.addSalt(doc, null, false);
        byte[] derivedKey = UsernameToken.generateDerivedKey("security", salt, 1000);
       
        //
        // Derived key encryption
        //
        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
        encrBuilder.setExternalKey(derivedKey, usernameToken.getID());
        encrBuilder.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        Document encryptedDoc = encrBuilder.build(doc, secHeader);
       
        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

    public void testLowIterationEncryption() throws Exception {
        Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
       
        UsernameToken usernameToken = new UsernameToken(true, doc, null);
        usernameToken.setName("bob");
        WSSConfig config = WSSConfig.getNewInstance();
        usernameToken.setID(config.getIdAllocator().createId("UsernameToken-", usernameToken));
       
        usernameToken.addIteration(doc, 500);
        byte[] salt = usernameToken.addSalt(doc, null, false);
        byte[] derivedKey = UsernameToken.generateDerivedKey("security", salt, 500);
       
        //
        // Derived key encryption
        //
        WSSecDKEncrypt encrBuilder = new WSSecDKEncrypt();
        encrBuilder.setSymmetricEncAlgorithm(WSConstants.AES_128);
        encrBuilder.setExternalKey(derivedKey, usernameToken.getID());
        encrBuilder.setCustomValueType(WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        Document encryptedDoc = encrBuilder.build(doc, secHeader);
       
        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

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.