Package com.sun.xml.ws.security

Examples of com.sun.xml.ws.security.IssuedTokenContext


         
        try{
            IssuedTokenManager manager = IssuedTokenManager.getInstance();
          
            String appliesTo = "http://localhost:8080/jaxws-fs/simple";
            IssuedTokenContext ctx = manager.createIssuedTokenContext(config, appliesTo);
            manager.getIssuedToken(ctx);
            Token issuedToken = ctx.getSecurityToken();
          
            return (Element)issuedToken.getTokenValue();
        }catch(Exception ex){
            throw new RuntimeException(ex);
        }
View Full Code Here


                        stsEndpoint, stsMexAddress);
            Status status = null;
            try{
                IssuedTokenManager manager = IssuedTokenManager.getInstance();

                IssuedTokenContext ctx = manager.createIssuedTokenContext(config, null);
                ctx.setTarget(new GenericToken(assertion));
                manager.validateIssuedToken(ctx);
                status = (Status)ctx.getOtherProperties().get(IssuedTokenContext.STATUS);
            }catch(Exception ex){
                throw new SAMLValidationException(ex);
            }
           
            if (!status.isValid()){
View Full Code Here

        // resolve the ProofKey here and set it into ProcessingContext
        //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
        String sctPolicyId = sctBinding.getUUID();       
        // this will work on the client side only
        //IssuedTokenContext ictx = context.getIssuedTokenContext(sctPolicyId);
        IssuedTokenContext ictx = null;
        String protocol = context.getWSSCVersion(context.getSecurityPolicyVersion());
        if(context.isClient()){           
            String sctId = context.getSCPolicyIDtoSctIdMap(sctPolicyId);
            SCTokenConfiguration config = new DefaultSCTokenConfiguration(protocol, sctId, !context.isExpired(), !context.isInboundMessage());
            ictx =IssuedTokenManager.getInstance().createIssuedTokenContext(config, null);
            try{
                IssuedTokenManager.getInstance().getIssuedToken(ictx);
            }catch(WSTrustException e){
                throw new XWSSecurityException(e);
            }
        }
        if (ictx == null) {
            // this will work on the server side
            String sctId = "";
            if(context instanceof JAXBFilterProcessingContext){
               
                Object sctObject = context.getExtraneousProperty(MessageConstants.INCOMING_SCT);
               
                if (sctObject == null) {
                    throw new XWSSecurityException("SecureConversation Session Context not Found");
                }
                if(sctObject instanceof com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken){
                    com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken sct = (com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken)sctObject;
                    sctId = sct.getSCId();
                }else if(sctObject instanceof SecurityContextToken){
                    SecurityContextToken sct = (SecurityContextToken)sctObject;
                    sctId = sct.getIdentifier().toString();
                }                                                               
            } else{                               
                SecurityContextToken sct = (SecurityContextToken)context.getExtraneousProperty(MessageConstants.INCOMING_SCT);
                if (sct == null) {
                    throw new XWSSecurityException("SecureConversation Session Context not Found");
                }               
                sctId = sct.getIdentifier().toString();
            }
           
            ictx = ((SessionManager)context.getExtraneousProperty("SessionManager")).getSecurityContext(sctId, !context.isExpired());
            java.net.URI identifier = null;
            String instance = null;
            String wsuId = null;
                   
            SecurityContextToken sct = (SecurityContextToken)ictx.getSecurityToken();
            if (sct != null){
                identifier = sct.getIdentifier();
                instance = sct.getInstance();
                wsuId = sct.getWsuId();
            }else{
                SecurityContextTokenInfo sctInfo = ictx.getSecurityContextTokenInfo();
                identifier = java.net.URI.create(sctInfo.getIdentifier());
                instance = sctInfo.getInstance();
                wsuId = sctInfo.getExternalId()
            }
           
            ictx.setSecurityToken(WSTrustElementFactory.newInstance(protocol).createSecurityContextToken(identifier, instance, wsuId));
        }
           
       
        if (ictx == null) {
            throw new XWSSecurityException("SecureConversation Session Context not Found");
View Full Code Here

    public static void resolveIssuedToken(FilterProcessingContext context, IssuedTokenKeyBinding itkb) throws XWSSecurityException {
        //resolve the ProofKey here and set it into ProcessingContext
        //String itPolicyId = itkb.getPolicyToken().getTokenId();
        String itPolicyId = itkb.getUUID();
        // this will work on the client side only
        IssuedTokenContext ictx = context.getIssuedTokenContext(itPolicyId);
        boolean clientSide = true;
        if (ictx == null) {
            // on the server we have the TrustCredentialHolder
            ictx = context.getTrustCredentialHolder();
            clientSide = false;
        }
       
        if (ictx == null) {
            throw new XWSSecurityException("Trust IssuedToken not Found");
        }
        if (ictx.getSecurityToken() instanceof GenericToken) {
            itkb.setRealId(((GenericToken)ictx.getSecurityToken()).getId());
        }

        context.setTrustContext(ictx);
        if (ictx.getProofKey() == null){
            //handle asymmetric issued key
            if (clientSide) {
                //TODO: change this later to use the Cert Alias
                X509Certificate cert = context.getSecurityEnvironment().getDefaultCertificate(
                        context.getExtraneousProperties());
                ictx.setRequestorCertificate(cert);
            else {
                //nothing todo on server side
            }
        }
    }
View Full Code Here

    }

    @SuppressWarnings("unchecked")
    private static Key resolveSCT(JAXBFilterProcessingContext wssContext, String scId, KeySelector.Purpose purpose) throws XWSSecurityException {

        IssuedTokenContext ctx = null;
        //String protocol = null;
        String protocol = wssContext.getWSSCVersion(wssContext.getSecurityPolicyVersion());
        if (wssContext.isClient()) {
            SCTokenConfiguration config = new DefaultSCTokenConfiguration(protocol, scId, !wssContext.isExpired(), !wssContext.isInboundMessage());
            ctx = IssuedTokenManager.getInstance().createIssuedTokenContext(config, null);
            try {
                IssuedTokenManager.getInstance().getIssuedToken(ctx);
            } catch (WSTrustException e) {
                throw new XWSSecurityException(e);
            }

            //Retrive the context from issuedTokenContextMap
//            Enumeration elements = wssContext.getIssuedTokenContextMap().elements();
//            while (elements.hasMoreElements()) {
//                IssuedTokenContext ictx = (IssuedTokenContext)elements.nextElement();
//                Object tok = ictx.getSecurityToken();
//                String ctxid = null;
//               
//                if (tok instanceof com.sun.xml.ws.security.SecurityContextToken) {
//                    ctxid = ((com.sun.xml.ws.security.SecurityContextToken)tok).getIdentifier().toString();
//                    if (ctxid.equals(scId)) {
//                        ctx = ictx;
//                        break;
//                    }
//                }
//            }
            if (ctx == null || ctx.getSecurityPolicy().isEmpty()) {
                // Return null as scId still needs to be resolved
                return null;
            }
        } else {
            //Retrive the context from Session Manager's cache
            System.out.println("context.isExpired >>> " + wssContext.isExpired());
            ctx = ((SessionManager) wssContext.getExtraneousProperty("SessionManager")).getSecurityContext(scId, !wssContext.isExpired());
            URI sctId = null;
            String sctIns = null;
            String wsuId = null;
            com.sun.xml.ws.security.SecurityContextToken sct = (com.sun.xml.ws.security.SecurityContextToken) ctx.getSecurityToken();
            if (sct != null){
                sctId = sct.getIdentifier();
                sctIns = sct.getInstance();
                wsuId = sct.getWsuId();
            }else {
                SecurityContextTokenInfo sctInfo = ctx.getSecurityContextTokenInfo();
                sctId = URI.create(sctInfo.getIdentifier());
                sctIns = sctInfo.getInstance();
                wsuId = sctInfo.getExternalId()
            }
            ctx.setSecurityToken(WSTrustElementFactory.newInstance(protocol).createSecurityContextToken(sctId, sctIns, wsuId));           
        }

        //update otherparty subject with bootstrap credentials.
        Subject subj = ctx.getRequestorSubject();
        if (subj != null) {
            // subj will be null if this is the client side execution
            if (wssContext.getExtraneousProperty(MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ) == null) {
                //do it only once
                wssContext.getSecurityEnvironment().updateOtherPartySubject(
                        SecurityUtil.getSubject(wssContext.getExtraneousProperties()), subj);
                wssContext.getExtraneousProperties().put(MessageConstants.SCBOOTSTRAP_CRED_IN_SUBJ, "true");
            }
        }


        byte[] proofKey = null;
        //com.sun.xml.ws.security.SecurityContextToken scToken = (com.sun.xml.ws.security.SecurityContextToken)ctx.getSecurityToken();
        if (wssContext.getWSCInstance() != null) {
            if (wssContext.isExpired()) {
                proofKey = ctx.getProofKey();
            } else {
                SecurityContextTokenInfo sctInstanceInfo = ctx.getSecurityContextTokenInfo();
                proofKey = sctInstanceInfo.getInstanceSecret(wssContext.getWSCInstance());
            }
        } else {
            proofKey = ctx.getProofKey();
        }
        wssContext.setExtraneousProperty(MessageConstants.INCOMING_SCT, ctx.getSecurityToken());


        if (proofKey == null) {
            throw new XWSSecurityException("Could not locate SecureConversation session for Id:" + scId);
        }
View Full Code Here

                    }
                } else if ( PolicyTypeUtil.issuedTokenKeyBinding(originalKeyBinding)) {
                   
                    IssuedTokenKeyBinding itk = (IssuedTokenKeyBinding)originalKeyBinding;
                   
                    IssuedTokenContext issuedTokenContext =  context.getTrustContext();
                   
                    //Get the IssuedToken and insert it into the message
                    GenericToken issuedToken = (GenericToken)issuedTokenContext.getSecurityToken();
                    SOAPElement tokenElem =  null;
                    SecurityTokenReference str = null;
                    Element strElem = null;
                   
                    // check if the token is already present
                    IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)originalKeyBinding;
                    //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                    String ikbPolicyId = ikb.getUUID();
                   
                    //Look for TrustToken in TokenCache
                    HashMap tokCache = context.getTokenCache();
                    Object tok = tokCache.get(ikbPolicyId);
                    SOAPElement issuedTokenElementFromMsg = null;
                    String iTokenType = ikb.getIncludeToken();
                    boolean includeIST =  (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                                                 ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                                                );
                   
                    if (includeIST && (issuedToken == null)) {
                        logger.log(Level.SEVERE, LogStringsMessages.WSS_1343_NULL_ISSUED_TOKEN());
                        throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                    }
                   
                    if (issuedToken != null) {
                        // treat the token as an Opaque entity and just insert the token into message
                        Element elem = (Element)issuedToken.getTokenValue();
                        if (tok == null) {
                            //TODO: remove these expensive conversions DOM Imports
                            tokenElem = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                            //FIX for Issue 26: We need an Id to cache and MS is not setting in some cases
                            String tokId = tokenElem.getAttribute("Id");
                            if ("".equals(tokId) &&
                                    MessageConstants.ENCRYPTED_DATA_LNAME.equals(tokenElem.getLocalName())) {
                                tokenElem.setAttribute("Id", secureMessage.generateId());
                            }
                            tokCache.put(ikbPolicyId, tokenElem);
                        } else {
                            // it will be SOAPElement retrieve its wsuId attr
                            String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                            issuedTokenElementFromMsg = (SOAPElement)secureMessage.getElementById(wsuId);
                            if (issuedTokenElementFromMsg == null) {
                                logger.log(Level.SEVERE,LogStringsMessages.WSS_1344_ERROR_LOCATE_ISSUE_TOKEN_MESSAGE());
                                throw new XWSSecurityException("Could not locate Issued Token in Message");
                            }
                        }
                    }
                   
                    if (includeIST) {
                        strElem = (Element)issuedTokenContext.getAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        strElem = (Element)issuedTokenContext.getUnAttachedSecurityTokenReference().getTokenValue();
                    }
                   
                    //TODO: remove these expensive conversions
                    Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
                    str = new SecurityTokenReference(XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), imported), false);
                   
                    if (originalKey != null) {
                        SecurityUtil.updateSamlVsKeyCache(str, context, originalKey);
                    }
                   
                    String dktId = keyBinding.getUUID();
                    if (dktId == null) {
                        dktId = secureMessage.generateId();
                    }
                   
                    DerivedKeyTokenHeaderBlock derivedKeyTokenHeaderBlock =
                            new DerivedKeyTokenHeaderBlock(
                            secureMessage.getSOAPPart(),
                            str,
                            Base64.encode(dkt.getNonce()),
                            dkt.getOffset(),
                            dkt.getLength(),
                            dktId);
                   
                   
                    if (issuedTokenElementFromMsg != null) {
                        SecurityHeader _secHeader = secureMessage.findOrCreateSecurityHeader();
                        _secHeader.insertBefore(derivedKeyTokenHeaderBlock, issuedTokenElementFromMsg.getNextSibling());
                    } else {
                        Node reflist = context.getCurrentRefList();
                        if (reflist != null) {
                            secureMessage.findOrCreateSecurityHeader().insertBefore(derivedKeyTokenHeaderBlock, reflist);
                            context.setCurrentReferenceList(null);
                        } else {
                            secureMessage.findOrCreateSecurityHeader().insertHeaderBlock(derivedKeyTokenHeaderBlock);
                        }
                    }
                   
                    // insert the Issued Token after the DKT
                    if (tokenElem != null) {
                        if (includeIST) {
                            secureMessage.findOrCreateSecurityHeader().insertHeaderBlockElement(tokenElem);
                        }
                        // also store the token in Packet.invocationProperties to be used by
                        // client side response processing
                        context.setIssuedSAMLToken(tokenElem);
                    }
                   
                    //Construct the STR for signature
                    DirectReference refSig = new DirectReference();
                    refSig.setURI("#"+dktId);
                    SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    sigTokenRef.setReference(refSig);
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                   
                    // set the next sibling to next sibling of derived key token
                    nextSibling = derivedKeyTokenHeaderBlock.getAsSoapElement().getNextSibling();
                    nxtSiblingContainer[0] = nextSibling;
                    return keyInfo;
                   
                } else if ( PolicyTypeUtil.samlTokenPolicy(originalKeyBinding)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1345_UNSUPPORTED_DERIVEDKEYS_SAML_TOKEN());
                    throw new UnsupportedOperationException("DerivedKeys with SAMLToken not yet supported");
                   
                } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(originalKeyBinding)) {
                    SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)originalKeyBinding;
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    SOAPElement sctElement = insertSCT(context, sctBinding, tokenRef);
                    String dktId = keyBinding.getUUID();
                    if (dktId == null) {
                        dktId = secureMessage.generateId();
                    }
                    String nonce = Base64.encode(dkt.getNonce());
                    DerivedKeyTokenHeaderBlock dktHeaderBlock =
                            new DerivedKeyTokenHeaderBlock(
                            securityHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                   
                    Node next = (sctElement != null) ? sctElement.getNextSibling() : null;
                   
                    if (next == null) {
                        Node reflist = context.getCurrentRefList();
                        if (reflist != null) {
                            next = reflist;
                            context.setCurrentReferenceList(null);
                        }
                    }
                   
                    SOAPElement dktElem = (SOAPElement)securityHeader.insertBefore(
                            dktHeaderBlock.getAsSoapElement(), next);
                    //Construct the STR for signature
                    DirectReference refSig = new DirectReference();
                    refSig.setURI("#"+dktId);
                    SecurityTokenReference sigTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    sigTokenRef.setReference(refSig);
                   
                    // signature should be below DKT
                    nextSibling = dktElem.getNextSibling();
                    nxtSiblingContainer[0] = nextSibling;
                   
                    keyInfo = dsigHelper.constructKeyInfo(signaturePolicy,sigTokenRef);
                    return keyInfo;
                }
               
            } else if ( PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
                //Get the IssuedToken and insert it into the message
                IssuedTokenContext issuedTokenContext =  context.getTrustContext();
                GenericToken issuedToken = (GenericToken)issuedTokenContext.getSecurityToken();
                SOAPElement tokenElem =  null;
                SecurityTokenReference str = null;
                Element strElem = null;
                SOAPElement issuedTokenElementFromMsg = null;
               
                // check if the token is already present
                IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)keyBinding;
                //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                String ikbPolicyId = ikb.getUUID();
               
                //Look for TrustToken in TokenCache
                HashMap tokCache = context.getTokenCache();
                Object tok = tokCache.get(ikbPolicyId);
                String iTokenType = ikb.getIncludeToken();
                boolean includeIST = (ikb.INCLUDE_ALWAYS_TO_RECIPIENT.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS_VER2.equals(iTokenType) ||
                          ikb.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(iTokenType)
                          );
                if (includeIST && (issuedToken == null)) {
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1343_NULL_ISSUED_TOKEN());
                    throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                }
               
                if (issuedToken != null) {
                    // treat the token as an Opaque entity and just insert the token into message
                    Element elem = (Element)issuedToken.getTokenValue();
                    if (tok == null) {
                        //TODO: remove these expensive conversions DOM Imports
                        tokenElem = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                        //FIX for Issue 26: We need an Id to cache and MS is not setting in some cases
                        String tokId = tokenElem.getAttribute("Id");
                        if ("".equals(tokId) &&
                                MessageConstants.ENCRYPTED_DATA_LNAME.equals(tokenElem.getLocalName())) {
                            tokenElem.setAttribute("Id", secureMessage.generateId());
                        }
                        tokCache.put(ikbPolicyId, tokenElem);
                    } else {
                        // it will be SOAPElement retrieve its wsuId attr
                        String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                        issuedTokenElementFromMsg = (SOAPElement)secureMessage.getElementById(wsuId);
                        if (issuedTokenElementFromMsg == null) {
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1344_ERROR_LOCATE_ISSUE_TOKEN_MESSAGE());
                            throw new XWSSecurityException("Could not locate Issued Token in Message");
                        }
                    }
                }
               
                if (includeIST) {
                    strElem = SecurityUtil.convertSTRToElement(issuedTokenContext.getAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    strElem = SecurityUtil.convertSTRToElement(issuedTokenContext.getUnAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                }
               
                if(strElem == null){
                    logger.log(Level.SEVERE, LogStringsMessages.WSS_1378_UNABLETO_REFER_ISSUE_TOKEN());
                    throw new XWSSecurityException("Cannot determine how to reference the Issued Token in the Message");
View Full Code Here

        SecurityContextTokenImpl sct = null;
        sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
        boolean tokenInserted = false;
        SOAPElement sctElement = null;
       
        IssuedTokenContext ictx = context.getSecureConversationContext();
       
        if (sct == null) {
            SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
            if (sct1 == null) {
                logger.log(Level.SEVERE, LogStringsMessages.WSS_1347_NULL_SECURE_CONVERSATION_TOKEN());
                throw new XWSSecurityException("SecureConversation Token not Found");
            }
           
View Full Code Here

            keyInfoStrategy = new KeyIdentifierStrategy(assertionId);
            keyInfoStrategy.insertKey(samlTokenRef, secureMsg);
           
        } else if ( PolicyTypeUtil.issuedTokenKeyBinding(keyBinding)) {
           
            IssuedTokenContext trustContext =  context.getTrustContext();
           
            //get the symmetric key for encryption
            try{
                _symmetricKey = new SecretKeySpec(trustContext.getProofKey(), SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
            } catch(Exception e){
                log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                throw new XWSSecurityException(e);
            }
           
            //Get the IssuedToken and insert it into the message
            GenericToken issuedToken = (GenericToken)trustContext.getSecurityToken();
           
            // check if the token is already present
            IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)keyBinding;
            //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
            String ikbPolicyId = ikb.getUUID();
           
            //Look for TrustToken in TokenCache
            HashMap tokCache = context.getTokenCache();
            Object tok = tokCache.get(ikbPolicyId);
           
            SecurityTokenReference str = null;
            Element strElem = null;
            String tokenVersion = ikb.getIncludeToken();
            includeIST = (IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_VER2.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(tokenVersion)
                          );
           
            if (includeIST && (issuedToken == null)) {
                log.log(Level.SEVERE, "WSS1217.null.IssueToken");
                throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
            }
           
            //trust token to be inserted into message
            if (issuedToken != null) {
                // treat the token as an Opaque entity and just insert the token into message
                Element elem = (Element)issuedToken.getTokenValue();
                //TODO: remove these expensive conversions DOM Imports
                if (tok == null) {
                    issuedTokenElement = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                    //Temp FIX for Issue#26: We need an Id to cache and MS not sending Id in some cases
                    String tokId = issuedTokenElement.getAttribute("Id");
                    if ("".equals(tokId) &&
                            MessageConstants.ENCRYPTED_DATA_LNAME.equals(issuedTokenElement.getLocalName())) {
                        issuedTokenElement.setAttribute("Id", secureMessage.generateId());
                    }
                    tokCache.put(ikbPolicyId, issuedTokenElement);
                } else {
                    issuedTokenInserted = true;
                    // it will be SOAPElement retrieve its wsuId attr
                    String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                    issuedTokenElementFromMsg = secureMessage.getElementById(wsuId);
                    if (issuedTokenElementFromMsg == null) {
                        log.log(Level.SEVERE, "WSS1218.unableto.locate.IssueToken.Message");
                        throw new XWSSecurityException("Could not locate Issued Token in Message");
                    }
                }
            }
           
            if (includeIST) {
                if (trustContext.getAttachedSecurityTokenReference() != null) {
                    strElem = SecurityUtil.convertSTRToElement(trustContext.getAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    log.log(Level.SEVERE, "WSS1219.unableto.refer.Attached.IssueToken");
                    throw new XWSSecurityException("Cannot determine how to reference the Attached Issued Token in the Message");
                }
            } else {
                //Trust Issued Token should not be in message at all, so use an external reference
                if (trustContext.getUnAttachedSecurityTokenReference() != null) {
                    strElem = SecurityUtil.convertSTRToElement(trustContext.getUnAttachedSecurityTokenReference().getTokenValue(), secureMessage.getSOAPPart());
                } else {
                    log.log(Level.SEVERE, "WSS1220.unableto.refer.Un-Attached.IssueToken");
                    throw new XWSSecurityException("Cannot determine how to reference the Un-Attached Issued Token in the Message");
                }
            }
           
            //TODO: remove these expensive conversions
            Element imported = (Element)secureMessage.getSOAPPart().importNode(strElem,true);
            issuedTokenRef = new SecurityTokenReference(XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), imported), false);
            SecurityUtil.updateSamlVsKeyCache(issuedTokenRef, context, _symmetricKey);
           
        } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(keyBinding)) {
           
            SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)keyBinding;
           
            //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
            String sctPolicyId = sctBinding.getUUID();
            //Look for SCT in TokenCache
            HashMap tokCache = context.getTokenCache();
            sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
           
            IssuedTokenContext ictx = context.getSecureConversationContext();
           
            if (sct == null) {
                SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
                if (sct1 == null) {
                    log.log(Level.SEVERE,"WSS1221.null.SecureConversationToken");
                    throw new XWSSecurityException("SecureConversation Token not Found");
                }
               
                sct = new SecurityContextTokenImpl(
                        secureMessage.getSOAPPart(), sct1.getIdentifier().toString(), sct1.getInstance(), sct1.getWsuId(), sct1.getExtElements());
                // put back in token cache
                tokCache.put(sctPolicyId, sct);
            } else {
                sctTokenInserted = true;
                // record the element
                sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
            }
           
            String sctWsuId = sct.getWsuId();
            if (sctWsuId == null) {
                sct.setId(secureMessage.generateId());
            }
            sctWsuId = sct.getWsuId();
           
            secConvRef = new SecurityTokenReference(secureMessage.getSOAPPart());
            DirectReference reference = new DirectReference();
            if (SecureConversationTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(sctBinding.getIncludeToken()) ||
                    SecureConversationTokenKeyBinding.INCLUDE_ALWAYS.equals(sctBinding.getIncludeToken())) {
               
                reference.setURI("#" + sctWsuId);
            } else {
                includeSCT = false;
                reference.setSCTURI(sct.getIdentifier().toString(), sct.getInstance());
            }
           
            secConvRef.setReference(reference);
            referenceType = MessageConstants.DIRECT_REFERENCE_TYPE;
            keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
           
            String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo);
            _symmetricKey = new SecretKeySpec(ictx.getProofKey(), jceAlgo);
           
           
        } else if (PolicyTypeUtil.derivedTokenKeyBinding(keyBinding)){
            DerivedTokenKeyBinding dtk = (DerivedTokenKeyBinding)keyBinding.clone();
            WSSPolicy originalKeyBinding = dtk.getOriginalKeyBinding();
           
            String algorithm = null;
            if(algSuite != null){
                algorithm = algSuite.getEncryptionAlgorithm();
            }
            //The offset and length to be used for DKT
            long offset = 0; // Default 0
            long length = SecurityUtil.getLengthFromAlgorithm(algorithm);
           
            if (PolicyTypeUtil.x509CertificateBinding(originalKeyBinding)) {
                //throw new XWSSecurityException("Asymmetric Binding with DerivedKeys under X509Token Policy Not Yet Supported");
            } else if ( PolicyTypeUtil.symmetricKeyBinding(originalKeyBinding)) {
                SymmetricKeyBinding skb = null;
                if ( context.getSymmetricKeyBinding() != null) {
                    skb = context.getSymmetricKeyBinding();
                    context.setSymmetricKeyBinding(null);
                } else{
                    skb = (SymmetricKeyBinding)originalKeyBinding;
                }
               
                if(sendEKSHA1){
                    String ekSha1Ref = getEKSHA1Ref(context);
                    //Construct a derivedKeyToken to be used
                    originalKey = skb.getSecretKey();
                    byte[] secret = originalKey.getEncoded();
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                    String dktId = secureMessage.generateId();
                    String nonce = Base64.encode(dkt.getNonce());
                    //get the symmetric key for encryption key from derivedkeyToken
                    try{
                        String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(algorithm);
                        _symmetricKey = dkt.generateSymmetricKey(jceAlgo);
                    } catch(Exception e){
                        log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                        throw new XWSSecurityException(e);
                    }
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    EncryptedKeySHA1Identifier refElem = new EncryptedKeySHA1Identifier(secureMessage.getSOAPPart());
                    refElem.setReferenceValue(ekSha1Ref);
                    tokenRef.setReference(refElem);
                   
                    //set the wsse11:TokenType attribute as required by WSS 1.1
                    //TODO: uncomment this once MS is ready to accpet this
                    //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                   
                    dktHeadrBlock =
                            new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength() ,dktId);
                   
                    //Construct the STR for Encryption
                    DirectReference reference = new DirectReference();
                    reference.setURI("#"+dktId);
                    ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    ekTokenRef.setReference(reference);
                } else if(wss11Sender || wss10){
                    dktSender = true;
                    originalKey = skb.getSecretKey();
                    if ( context.getX509CertificateBinding() != null ) {
                        certificateBinding = context.getX509CertificateBinding();
                        context.setX509CertificateBinding(null);
                        _x509Cert = certificateBinding.getX509Certificate();
                    }
                    _x509Cert = certificateBinding.getX509Certificate();
                    referenceType =  certificateBinding.getReferenceType();
                    keyInfoStrategy = KeyInfoStrategy.getInstance(referenceType);
                    _exportCertificate = true;
                    keyInfoStrategy.setCertificate(_x509Cert);
                    x509TokenId = certificateBinding.getUUID();
                    if(x509TokenId == null || x509TokenId.equals("")){
                        x509TokenId = secureMsg.generateId();
                    }
                   
                    if(log.isLoggable(Level.FINEST)){
                        log.log(Level.FINEST, "Certificate was "+_x509Cert);
                        log.log(Level.FINEST, "BinaryToken ID "+x509TokenId);
                    }
                   
                   
                    HashMap tokenCache = context.getTokenCache();
                    HashMap insertedX509Cache = context.getInsertedX509Cache();
                   
                    SecurityUtil.checkIncludeTokenPolicy(context, certificateBinding, x509TokenId);
                   
                    // ReferenceType adjustment in checkIncludeTokenPolicy is also currently
                    // causing an insertion of the X509 into the Message
                    X509SecurityToken insertedx509 =
                            (X509SecurityToken)context.getInsertedX509Cache().get(x509TokenId);
                   
                    // this one is used to determine if the whole BST + EK + DKT(opt)
                    // has been inserted by another filter such as Encryption running before
                    X509SecurityToken token = (X509SecurityToken)tokenCache.get(x509TokenId);
                    if(token == null){
                        if (insertedx509 != null) {
                            token = insertedx509;
                            tokenCache.put(x509TokenId, insertedx509);
                        } else {
                            String valueType = certificateBinding.getValueType();
                            if(valueType==null||valueType.equals("")){
                                //default valueType for X509 as v3
                                valueType = MessageConstants.X509v3_NS;
                            }
                            token = new X509SecurityToken(secureMsg.getSOAPPart(),_x509Cert,x509TokenId, valueType);
                            tokenCache.put(x509TokenId, token);
                        }
                        context.setCurrentSecret(originalKey);
                        //Store SymmetricKey generated in ProcessingContext
                        context.setExtraneousProperty("SecretKey", originalKey);
                    } else{
                        skbX509TokenInserted = true;
                        originalKey = context.getCurrentSecret();
                    }
                    //
                    if(insertedx509 == null){
                        if(MessageConstants.DIRECT_REFERENCE_TYPE.equals(referenceType)){
                            secureMsg.findOrCreateSecurityHeader().insertHeaderBlock(token);
                            insertedX509Cache.put(x509TokenId, token);
                            x509TokenElement = secureMsg.findOrCreateSecurityHeader().getNextSiblingOfTimestamp();
                        }
                    } else{
                        //x509TokenElement = secureMsg.getElementByWsuId(x509TokenId);
                        x509TokenElement = insertedx509;
                    }
                    //}
                   
                    //Construct a derivedKeyToken to be used
                    byte[] secret = originalKey.getEncoded();
                    DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                    String dktId = secureMessage.generateId();
                    String nonce = Base64.encode(dkt.getNonce());
                    //get the symmetric key for encryption key from derivedkeyToken
                    try{
                        String jceAlgo = SecurityUtil.getSecretKeyAlgorithm(algorithm);
                        _symmetricKey = dkt.generateSymmetricKey(jceAlgo);
                    } catch(Exception e){
                        log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                        throw new XWSSecurityException(e);
                    }
                   
                    //STR for DerivedKeyToken
                    SecurityTokenReference tokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    DirectReference reference = new DirectReference();
                    //TODO: PLUGFEST Commeting for now as Microsoft setting the EncryptedKey type on reference valueType
                    //tokenRef.setTokenType(MessageConstants.EncryptedKey_NS);
                    //set id of encrypted key in STR of DKT
                    insertedEkId = (String)ekCache.get(x509TokenId);
                    if(insertedEkId == null)
                        insertedEkId = ekId;
                    reference.setURI("#"+insertedEkId);
                    reference.setValueType(MessageConstants.EncryptedKey_NS);
                    tokenRef.setReference(reference);
                    dktHeadrBlock =
                            new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), tokenRef, nonce, dkt.getOffset(), dkt.getLength(), dktId);
                   
                    //Construct the STR for Encryption
                    DirectReference refEnc = new DirectReference();
                    refEnc.setURI("#"+dktId);
                    ekTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                    ekTokenRef.setReference(refEnc);
                }
            } else if (PolicyTypeUtil.secureConversationTokenKeyBinding(originalKeyBinding)) {
               
                sctWithDKT = true;
               
                SecureConversationTokenKeyBinding sctBinding = (SecureConversationTokenKeyBinding)originalKeyBinding;
                //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
                String sctPolicyId = sctBinding.getUUID();
                //Look for SCT in TokenCache
                HashMap tokCache = context.getTokenCache();
                sct = (SecurityContextTokenImpl)tokCache.get(sctPolicyId);
               
                IssuedTokenContext ictx = context.getSecureConversationContext();
               
                if (sct == null) {
                    SecurityContextToken sct1 =(SecurityContextToken)ictx.getSecurityToken();
                    if (sct1 == null) {
                        log.log(Level.SEVERE, "WSS1221.null.SecureConversationToken");
                        throw new XWSSecurityException("SecureConversation Token not Found");
                    }
                   
                    sct = new SecurityContextTokenImpl(
                            secureMessage.getSOAPPart(), sct1.getIdentifier().toString(), sct1.getInstance(), sct1.getWsuId(), sct1.getExtElements());
                    // put back in token cache
                    tokCache.put(sctPolicyId, sct);
                } else {
                    sctTokenInserted = true;
                    // record the element
                    sctElement = secureMessage.getElementByWsuId(sct.getWsuId());
                }
               
                String sctWsuId = sct.getWsuId();
                if (sctWsuId == null) {
                    sct.setId(secureMessage.generateId());
                }
                sctWsuId = sct.getWsuId();
               
                byte[] secret =  context.getSecureConversationContext().getProofKey();
                DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, secret);
                String dktId = secureMessage.generateId();
                String nonce = Base64.encode(dkt.getNonce());
                //get the symmetric key for encryption key from derivedkeyToken
                try{
                    _symmetricKey = dkt.generateSymmetricKey(SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
                //STR for DerivedKeyToken
                SecurityTokenReference secRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                DirectReference reference = new DirectReference();
                if (SecureConversationTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(sctBinding.getIncludeToken()) ||
                        SecureConversationTokenKeyBinding.INCLUDE_ALWAYS.equals(sctBinding.getIncludeToken())) {
                   
                    reference.setURI("#" + sctWsuId);
                } else {
                    includeSCT = false;
                    reference.setSCTURI(sct.getIdentifier().toString(), sct.getInstance());
                }
                secRef.setReference(reference);
                dktHeadrBlock =
                        new DerivedKeyTokenHeaderBlock(_secHeader.getOwnerDocument(), secRef, nonce, dkt.getOffset(), dkt.getLength(),dktId);
               
                //Construct the STR for Encryption
                DirectReference refEnc = new DirectReference();
                refEnc.setURI("#"+dktId);
                dktSctTokenRef = new SecurityTokenReference(secureMessage.getSOAPPart());
                dktSctTokenRef.setReference(refEnc);
               
            } else if (PolicyTypeUtil.issuedTokenKeyBinding(originalKeyBinding)) {
               
                issuedWithDKT = true;
               
                IssuedTokenContext trustContext =  context.getTrustContext();
                DerivedKeyToken dkt = new DerivedKeyTokenImpl(offset, length, trustContext.getProofKey());
                String dktId = secureMessage.generateId();
                String nonce = Base64.encode(dkt.getNonce());
               
                //get the symmetric key for encryption
                Key origKey = null;
                try{
                    origKey = new SecretKeySpec(trustContext.getProofKey(), SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
               
               
                //get the symmetric key for encryption key from derivedkeyToken
                try{
                    _symmetricKey = dkt.generateSymmetricKey(SecurityUtil.getSecretKeyAlgorithm(dataEncAlgo));
                } catch(Exception e){
                    log.log(Level.SEVERE, "WSS1216.unableto.get.symmetrickey.Encryption");
                    throw new XWSSecurityException(e);
                }
               
                //Get the IssuedToken and insert it into the message
                GenericToken issuedToken = (GenericToken)trustContext.getSecurityToken();
               
                // check if the token is already present
                IssuedTokenKeyBinding ikb = (IssuedTokenKeyBinding)originalKeyBinding;
                //String ikbPolicyId = ikb.getPolicyToken().getTokenId();
                String ikbPolicyId = ikb.getUUID();
                //Look for TrustToken in TokenCache
                HashMap tokCache = context.getTokenCache();
                Object tok = tokCache.get(ikbPolicyId);
               
                SecurityTokenReference str = null;
                Element strElem = null;
                String tokenVersion = ikb.getIncludeToken();
                includeIST = (IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_VER2.equals(tokenVersion) ||
                          IssuedTokenKeyBinding.INCLUDE_ALWAYS_TO_RECIPIENT_VER2.equals(tokenVersion)
                          );
               
                if (includeIST && (issuedToken == null)) {
                    log.log(Level.SEVERE, "WSS1217.null.IssueToken");
                    throw new XWSSecurityException("Issued Token to be inserted into the Message was Null");
                }
               
                if (issuedToken != null) {
                    // treat the token as an Opaque entity and just insert the token into message
                    Element elem = (Element)issuedToken.getTokenValue();
                    //TODO: remove these expensive conversions DOM Imports
                    if (tok == null) {
                        issuedTokenElement = XMLUtil.convertToSoapElement(secureMessage.getSOAPPart(), elem);
                        //Temp FIX for Issue#26: We need an Id to cache and MS not sending Id in some cases
                        String tokId = issuedTokenElement.getAttribute("Id");
                        if ("".equals(tokId) &&
                                MessageConstants.ENCRYPTED_DATA_LNAME.equals(issuedTokenElement.getLocalName())) {
                            issuedTokenElement.setAttribute("Id", secureMessage.generateId());
                        }
                        tokCache.put(ikbPolicyId, issuedTokenElement);
                    } else {
                        issuedTokenInserted = true;
                        // it will be SOAPElement retrieve its wsuId attr
                        String wsuId = SecurityUtil.getWsuIdOrId((Element)tok);
                        issuedTokenElementFromMsg = secureMessage.getElementById(wsuId);
                        if (issuedTokenElementFromMsg == null) {
                            log.log(Level.SEVERE, "WSS1218.unableto.locate.IssueToken.Message");
                            throw new XWSSecurityException("Could not locate Issued Token in Message");
                        }
                    }
                }
               
                if (includeIST) {
                    if (trustContext.getAttachedSecurityTokenReference() != null) {
                        strElem = (Element)trustContext.getAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        log.log(Level.SEVERE, "WSS1219.unableto.refer.Attached.IssueToken");
                        throw new XWSSecurityException("Cannot determine how to reference the Attached Issued Token in the Message");
                    }
                } else {
                    //Trust Issued Token should not be in message at all, so use an external reference
                    if (trustContext.getUnAttachedSecurityTokenReference() != null) {
                        strElem = (Element)trustContext.getUnAttachedSecurityTokenReference().getTokenValue();
                    } else {
                        log.log(Level.SEVERE, "WSS1220.unableto.refer.Un-Attached.IssueToken");
                        throw new XWSSecurityException("Cannot determine how to reference the Un-Attached Issued Token in the Message");
                    }
                }
View Full Code Here

                        UsernameTokenHeader ut = new UsernameTokenHeader(message, creator, (HashMap) currentParentNS, staxIF);
                        ut.validate(context);
                        context.getSecurityContext().getProcessedSecurityHeaders().add(ut);
                        context.getInferredSecurityPolicy().append(ut.getPolicy());
                        if (context.isTrustMessage() && !context.isClient()) {
                            IssuedTokenContext ctx;
                            if (context.getTrustContext() == null) {
                                ctx = new IssuedTokenContextImpl();
                                if (context.isSecure()) {
                                    ctx.setAuthnContextClass(MessageConstants.PASSWORD_PROTECTED_TRANSPORT_AUTHTYPE);
                                } else {
                                    ctx.setAuthnContextClass(MessageConstants.PASSWORD_AUTH_TYPE);
                                }
                                context.setTrustContext(ctx);
                            } else {
                                ctx = context.getTrustContext();
                                if (ctx.getAuthnContextClass() != null) {
                                    if (context.isSecure()) {
                                        ctx.setAuthnContextClass(MessageConstants.PASSWORD_PROTECTED_TRANSPORT_AUTHTYPE);
                                    } else {
                                        ctx.setAuthnContextClass(MessageConstants.PASSWORD_AUTH_TYPE);
                                    }
                                    context.setTrustContext(ctx);
                                }
                            }
                        }
                        break;
                    }
                    case BINARYSECURITY_TOKEN_ELEMENT: {
                        String valueType = message.getAttributeValue(null, MessageConstants.WSE_VALUE_TYPE);
                        if (MessageConstants.KERBEROS_V5_GSS_APREQ_1510.equals(valueType)
                                || MessageConstants.KERBEROS_V5_GSS_APREQ.equals(valueType)) {
                            KerberosBinarySecurityToken kbst = new KerberosBinarySecurityToken(message, creator, (HashMap) currentParentNS, staxIF);
                            WSSPolicy policy = kbst.getPolicy();
                            ((TokenValidator) kbst).validate(context);
                            processedHeaders.add(kbst);
                            context.getInferredSecurityPolicy().append(kbst.getPolicy());
                            if (context.isTrustMessage() && !context.isClient()) {
                                IssuedTokenContext ctx;
                                if (context.getTrustContext() == null) {
                                    ctx = new IssuedTokenContextImpl();
                                    ctx.setAuthnContextClass(MessageConstants.KERBEROS_AUTH_TYPE);
                                    context.setTrustContext(ctx);
                                } else {
                                    ctx = context.getTrustContext();
                                    if (ctx.getAuthnContextClass() != null) {
                                        ctx.setAuthnContextClass(MessageConstants.KERBEROS_AUTH_TYPE);
                                        context.setTrustContext(ctx);
                                    }
                                }
                            }
                        } else if (MessageConstants.X509v3_NS.equals(valueType)
                                || MessageConstants.X509v1_NS.equals(valueType)
                                || valueType == null) /*null takes as X509 BST */ {
                            X509BinarySecurityToken bst = new X509BinarySecurityToken(message, creator, (HashMap) currentParentNS, staxIF);
                            WSSPolicy policy = bst.getPolicy();
                            ((TokenValidator) bst).validate(context);
                            processedHeaders.add(bst);
                            context.getInferredSecurityPolicy().append(bst.getPolicy());
                            if (context.isTrustMessage() && !context.isClient()) {
                                IssuedTokenContext ctx;
                                if (context.getTrustContext() == null) {
                                    ctx = new IssuedTokenContextImpl();
                                    ctx.setAuthnContextClass(MessageConstants.X509_AUTH_TYPE);
                                    context.setTrustContext(ctx);
                                } else {
                                    ctx = context.getTrustContext();
                                    if (ctx.getAuthnContextClass() != null) {
                                        ctx.setAuthnContextClass(MessageConstants.X509_AUTH_TYPE);
                                        context.setTrustContext(ctx);
                                    }
                                }
                            }
                        } else {
                            //unrecognized valuetype
                            logger.log(Level.SEVERE, LogStringsMessages.WSS_1616_UNRECOGNIZED_BST_VALUETYPE(valueType));
                            throw new XWSSecurityException(LogStringsMessages.WSS_1616_UNRECOGNIZED_BST_VALUETYPE(valueType));
                        }

                        break;
                    }
                    case ENCRYPTED_KEY_ELEMENT: {
                        EncryptedKey ek = new EncryptedKey(message, context, (HashMap) currentParentNS);
                        ArrayList<String> list = (ArrayList) ek.getPendingReferenceList();
                        if (list != null) {
                            findAndReplaceED(list, ek);
                            if (ek.getPendingReferenceList().size() > 0) {
                                if (pendingElement == null) {
                                    pendingElement = ek;
                                }//else{
                                addSecurityHeader(ek);
                                //}
                            }
                        } else {
                            addSecurityHeader(ek);
                        }
                        if (ek.getPolicy() != null) {
                            context.getInferredSecurityPolicy().append(ek.getPolicy());
                        }
                        break;
                    }
                    case ENCRYPTED_DATA_ELEMENT: {
                        EncryptedData ed = new EncryptedData(message, context, currentParentNS);
                        handleEncryptedData(ed, currentParentNS);
                        break;
                    }

                    case ENCRYPTED_HEADER_ELEMENT: {
                        throw new XWSSecurityException("wsse11:EncryptedHeader not allowed inside SecurityHeader");
                        //break;
                    }

                    case REFERENCE_LIST_ELEMENT: {
                        ReferenceListHeader refList = new ReferenceListHeader(message, context);
                        if (pendingElement == null) {
                            pendingElement = refList;
                        } else {
                            addSecurityHeader(refList);
                        }

                        context.getInferredSecurityPolicy().append(refList.getPolicy());
                        break;
                    }
                    case SIGNATURE_ELEMENT: {
                        Signature sig = new Signature(context, currentParentNS, creator);
                        sig.process(message);
                        if (!sig.isValidated()) {
                            if (pendingElement == null) {
                                pendingElement = sig;
                            } else {
                                addSecurityHeader(sig);
                            }
                        } else {
                            if (!processedHeaders.contains(sig)) {
                                processedHeaders.add(sig);
                            }
                        }
                        context.getInferredSecurityPolicy().append(sig.getPolicy());
                        break;
                    }
                    case DERIVED_KEY_ELEMENT: {
                        DerivedKeyToken dkt = new DerivedKeyToken(message, context, (HashMap) currentParentNS);
                        processedHeaders.add(dkt);
                        break;
                    }
                    case SIGNATURE_CONFIRMATION_ELEMENT: {
                        SignatureConfirmation signConfirm = new SignatureConfirmation(message, creator, (HashMap) currentParentNS, staxIF);
                        WSSPolicy policy = signConfirm.getPolicy();
                        signConfirm.validate(context);
                        processedHeaders.add(signConfirm);
                        context.getInferredSecurityPolicy().append(signConfirm.getPolicy());
                        break;
                    }
                    case SECURITY_CONTEXT_TOKEN: {
                        SecurityContextToken sct = new SecurityContextToken(message, context, (HashMap) currentParentNS);
                        processedHeaders.add(sct);
                        break;
                    }
                    case SAML_ASSERTION_ELEMENT: {
                        SAMLAssertion samlAssertion = new SAMLAssertion(message, context, null, (HashMap) currentParentNS);
                        processedHeaders.add(samlAssertion);
                        if (samlAssertion.isHOK()) {
                            if (!samlAssertion.validateSignature()) {
                                logger.log(Level.SEVERE, LogStringsMessages.WSS_1614_SAML_SIGNATURE_INVALID());
                                throw SOAPUtil.newSOAPFaultException(MessageConstants.WSSE_FAILED_AUTHENTICATION,
                                        LogStringsMessages.WSS_1614_SAML_SIGNATURE_INVALID(),
                                        new Exception(LogStringsMessages.WSS_1614_SAML_SIGNATURE_INVALID()));
                            }
                        }
                        samlAssertion.validate(context);
                        samlAssertion.getKey();
                        // Set in the extraneous property only if not already set
                        // workaround in the case where there are two HOK assertions in the request
                        if (context.getExtraneousProperty(MessageConstants.INCOMING_SAML_ASSERTION) == null && samlAssertion.isHOK()) {
                            context.getExtraneousProperties().put(MessageConstants.INCOMING_SAML_ASSERTION, samlAssertion);
                        }
                        context.getInferredSecurityPolicy().append(samlAssertion.getPolicy());
                        if (context.isTrustMessage() && !context.isClient()) {
                            IssuedTokenContext ctx;
                            if (context.getTrustContext() == null) {
                                ctx = new IssuedTokenContextImpl();
                                ctx.setAuthnContextClass(MessageConstants.PREVIOUS_SESSION_AUTH_TYPE);
                                context.setTrustContext(ctx);
                            } else {
                                ctx = context.getTrustContext();
                                if (ctx.getAuthnContextClass() != null) {
                                    ctx.setAuthnContextClass(MessageConstants.PREVIOUS_SESSION_AUTH_TYPE);
                                    context.setTrustContext(ctx);
                                }
                            }
                        }
//                        } else if (!context.isTrustMessage()) {
View Full Code Here

            }
            samlAssertion.validate(context);
            samlAssertion.getKey();
            context.getExtraneousProperties().put(MessageConstants.INCOMING_SAML_ASSERTION, samlAssertion);
            if (context.isTrustMessage() && !context.isClient()) {
                IssuedTokenContext ctx;
                if (context.getTrustContext() == null) {
                    ctx = new IssuedTokenContextImpl();
                    ctx.setAuthnContextClass(MessageConstants.PREVIOUS_SESSION_AUTH_TYPE);
                    context.setTrustContext(ctx);
                } else {
                    ctx = context.getTrustContext();
                    if (ctx.getAuthnContextClass() != null) {
                        ctx.setAuthnContextClass(MessageConstants.PREVIOUS_SESSION_AUTH_TYPE);
                        context.setTrustContext(ctx);
                    }
                }
            }
            return true;
View Full Code Here

TOP

Related Classes of com.sun.xml.ws.security.IssuedTokenContext

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.