FileDocCategorySizeDatePackage
IssueSamlTokenContractImpl.javaAPI DocExample26470Tue May 29 16:56:58 BST 2007com.sun.xml.ws.security.trust.impl

IssueSamlTokenContractImpl

public class IssueSamlTokenContractImpl extends IssueSamlTokenContract

Fields Summary
private static final Logger
log
private static final String
SAML_HOLDER_OF_KEY
Constructors Summary
Methods Summary
private com.sun.org.apache.xml.internal.security.keys.KeyInfocreateKeyInfo(java.lang.String keyType, java.security.cert.X509Certificate serCert, com.sun.xml.ws.security.IssuedTokenContext ctx, java.lang.String appliesTo)

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        
        Document doc = null;
        try{
            doc = docFactory.newDocumentBuilder().newDocument();
        }catch(ParserConfigurationException ex){
            log.log(Level.SEVERE, 
                    LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
            throw new WSTrustException(LogStringsMessages.WST_0039_ERROR_CREATING_DOCFACTORY(), ex);
        }
        
        final KeyInfo keyInfo = new KeyInfo(doc);
        if (WSTrustConstants.SYMMETRIC_KEY.equals(keyType)){
            final byte[] key = ctx.getProofKey();
            if (!stsConfig.getEncryptIssuedToken() && stsConfig.getEncryptIssuedKey()){
                final EncryptedKey encKey = encryptKey(doc, key, serCert, appliesTo);
                try{
                    keyInfo.add(encKey);
                } catch (XMLEncryptionException ex) {
                    log.log(Level.SEVERE,
                            LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
                    throw new WSTrustException(LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
                }
            }else{
                final BinarySecret secret = eleFac.createBinarySecret(key, BinarySecret.SYMMETRIC_KEY_TYPE);
                final Element bsEle= eleFac.toElement(secret,doc);
                keyInfo.addUnknownElement(bsEle);
            }
        }else if(WSTrustConstants.PUBLIC_KEY.equals(keyType)){
            final X509Data x509data = new X509Data(doc);
            try{
                x509data.addCertificate(ctx.getRequestorCertificate());
            }catch(com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException ex){
                log.log(Level.SEVERE, LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT(), ex);
                throw new WSTrustException(LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT(), ex);
            }
            keyInfo.add(x509data);
        }
        
        return keyInfo;
    
private com.sun.xml.wss.saml.AssertioncreateSAML11Assertion(java.lang.String assertionId, java.lang.String issuer, java.lang.String appliesTo, com.sun.org.apache.xml.internal.security.keys.KeyInfo keyInfo, java.util.Map claimedAttrs)

        Assertion assertion = null;
        try{
            final SAMLAssertionFactory samlFac = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML1_1);
            
            final GregorianCalendar issuerInst = new GregorianCalendar();
            final GregorianCalendar notOnOrAfter = new GregorianCalendar();
            notOnOrAfter.add(Calendar.MILLISECOND, (int)stsConfig.getIssuedTokenTimeout());
            
            final Conditions conditions =
                    samlFac.createConditions(issuerInst, notOnOrAfter, null, null, null);
            final Advice advice = samlFac.createAdvice(null, null, null);
            
            final List<String> confirmMethods = new ArrayList<String>();
            confirmMethods.add(SAML_HOLDER_OF_KEY);
            
            final SubjectConfirmation subjectConfirm = samlFac.createSubjectConfirmation(
                    confirmMethods, null, keyInfo.getElement());
            
            com.sun.xml.wss.saml.Subject subj = null;
            final List<Attribute> attrs = new ArrayList<Attribute>();
            final Set<Map.Entry<QName, List<String>>> entries = claimedAttrs.entrySet();
            for(Map.Entry<QName, List<String>> entry : entries){
                final QName attrKey = (QName)entry.getKey();
                final List<String> values = (List<String>)entry.getValue();
                if (values != null && values.size() > 0){
                    if (STSAttributeProvider.NAME_IDENTIFIER.equals(attrKey.getLocalPart()) && subj == null){
                        final NameIdentifier nameId = samlFac.createNameIdentifier(values.get(0), attrKey.getNamespaceURI(), null);
                        subj = samlFac.createSubject(nameId, subjectConfirm);
                    }
                    else{
                        final Attribute attr = samlFac.createAttribute(attrKey.getLocalPart(), attrKey.getNamespaceURI(), values);
                        attrs.add(attr);
                    }
                }
            }
            
            final List<Object> statements = new ArrayList<Object>();
            if (attrs.isEmpty()){
                final AuthenticationStatement statement = samlFac.createAuthenticationStatement(null, issuerInst, subj, null, null);
                statements.add(statement); 
            }else{
                final AttributeStatement statement = samlFac.createAttributeStatement(subj, attrs);
                statements.add(statement);
            }
            assertion =
                    samlFac.createAssertion(assertionId, issuer, issuerInst, conditions, advice, statements);
        }catch(SAMLException ex){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
            throw new WSTrustException(
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
        }catch(XWSSecurityException ex){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
            throw new WSTrustException(
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
        }
        
        return assertion;
    
private com.sun.xml.wss.saml.AssertioncreateSAML20Assertion(java.lang.String assertionId, java.lang.String issuer, java.lang.String appliesTo, com.sun.org.apache.xml.internal.security.keys.KeyInfo keyInfo, java.util.Map claimedAttrs)

        Assertion assertion = null;
        try{
            final SAMLAssertionFactory samlFac = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML2_0);
            
            // Create Conditions
            final GregorianCalendar issueInst = new GregorianCalendar();
            final GregorianCalendar notOnOrAfter = new GregorianCalendar();
            notOnOrAfter.add(Calendar.MILLISECOND, (int)stsConfig.getIssuedTokenTimeout());
            
            final Conditions conditions = samlFac.createConditions(issueInst, notOnOrAfter, null, null, null, null);
            
            // Create Subject
            
            // SubjectConfirmationData subjComfData = samlFac.createSubjectConfirmationData(
            // null, null, null, null, appliesTo, keyInfo.getElement());
            
            final KeyInfoConfirmationData keyInfoConfData = samlFac.createKeyInfoConfirmationData(keyInfo.getElement());
            
            final SubjectConfirmation subjectConfirm = samlFac.createSubjectConfirmation(
                    null, keyInfoConfData, SAML_HOLDER_OF_KEY);
            
            com.sun.xml.wss.saml.Subject subj = null;
            final List<Attribute> attrs = new ArrayList<Attribute>();
            final Set<Map.Entry<QName, List<String>>> entries = claimedAttrs.entrySet();
            for(Map.Entry<QName, List<String>> entry : entries){
                final QName attrKey = (QName)entry.getKey();
                final List<String> values = (List<String>)entry.getValue();
                if (values != null && values.size() > 0){
                    if (STSAttributeProvider.NAME_IDENTIFIER.equals(attrKey.getLocalPart()) && subj == null){
                        final NameID nameId = samlFac.createNameID(values.get(0), attrKey.getNamespaceURI(), null);
                        subj = samlFac.createSubject(nameId, subjectConfirm);
                    }
                    else{
                        final Attribute attr = samlFac.createAttribute(attrKey.getLocalPart(), values);
                        attrs.add(attr);
                    }
                }
            }
        
            final List<Object> statements = new ArrayList<Object>();
            if (attrs.isEmpty()){
                // To Do: create AuthnContext with proper content. Currently what 
                // we have is a place holder.
                AuthnContext ctx = samlFac.createAuthnContext();
                final AuthnStatement statement = samlFac.createAuthnStatement(issueInst, null, ctx);
                statements.add(statement); 
            }else{
                final AttributeStatement statement = samlFac.createAttributeStatement(attrs);
                statements.add(statement);
            }
            
            final NameID issuerID = samlFac.createNameID(issuer, null, null);
            
            // Create Assertion
            assertion =
                    samlFac.createAssertion(assertionId, issuerID, issueInst, conditions, null, subj, statements);
        }catch(SAMLException ex){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
            throw new WSTrustException(
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
        }catch(XWSSecurityException ex){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
            throw new WSTrustException(
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
        }
        
        return assertion;
    
public com.sun.xml.ws.security.TokencreateSAMLAssertion(java.lang.String appliesTo, java.lang.String tokenType, java.lang.String keyType, java.lang.String assertionId, java.lang.String issuer, java.util.Map claimedAttrs, com.sun.xml.ws.security.IssuedTokenContext context)

    
                               
        Token token = null;
        
        // Get the service certificate
        TrustSPMetadata spMd = stsConfig.getTrustSPMetadata(appliesTo);
        if (spMd == null){
            spMd = stsConfig.getTrustSPMetadata("default");
        }
        final X509Certificate serCert = getServiceCertificate(spMd, appliesTo);
            
        // Create the KeyInfo for SubjectConfirmation
        final KeyInfo keyInfo = createKeyInfo(keyType, serCert, context, appliesTo);
            
        // Create SAML assertion
        Assertion assertion = null;
        if (WSTrustConstants.SAML10_ASSERTION_TOKEN_TYPE.equals(tokenType)||
            WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE.equals(tokenType)){
            assertion = createSAML11Assertion(assertionId, issuer, appliesTo, keyInfo, claimedAttrs);
        } else if (WSTrustConstants.SAML20_ASSERTION_TOKEN_TYPE.equals(tokenType)){
            assertion = createSAML20Assertion(assertionId, issuer, appliesTo, keyInfo, claimedAttrs);
        } else{
            log.log(Level.SEVERE, LogStringsMessages.WST_0031_UNSUPPORTED_TOKEN_TYPE(tokenType, appliesTo));
            throw new WSTrustException(LogStringsMessages.WST_0031_UNSUPPORTED_TOKEN_TYPE(tokenType, appliesTo));
        }
            
        // Get the STS's certificate and private key
        Object[] stsCertsAndPrikey = getSTSCertAndPrivateKey();
        final X509Certificate stsCert = (X509Certificate)stsCertsAndPrikey[0];
        final PrivateKey stsPrivKey = (PrivateKey)stsCertsAndPrikey[1];
            
        // Sign the assertion with STS's private key
        Element signedAssertion = null;
        try{
            signedAssertion = assertion.sign(stsCert, stsPrivKey);
        }catch (SAMLException ex){
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
            throw new WSTrustException(
                    LogStringsMessages.WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
        }
            
        //javax.xml.bind.Unmarshaller u = eleFac.getContext().createUnmarshaller();
        //JAXBElement<AssertionType> aType = u.unmarshal(signedAssertion, AssertionType.class);
        //assertion =  new com.sun.xml.wss.saml.assertion.saml11.jaxb20.Assertion(aType.getValue());
        //token = new GenericToken(signedAssertion);
            
        if (stsConfig.getEncryptIssuedToken()){
            Element encData = encryptToken(signedAssertion, serCert, appliesTo);
            token = new GenericToken(encData);
                //JAXBElement<EncryptedDataType> eEle = u.unmarshal(cipher.martial(encData), EncryptedDataType.class);
                //return eEle.getValue();
        }else{
                token = new GenericToken(signedAssertion);
        }

        return token;
    
private com.sun.org.apache.xml.internal.security.encryption.EncryptedKeyencryptKey(org.w3c.dom.Document doc, byte[] encryptedKey, java.security.cert.X509Certificate cert, java.lang.String appliesTo)

        EncryptedKey encKey = null;
        try{
            final PublicKey pubKey = cert.getPublicKey();
            final XMLCipher cipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP);
            cipher.init(XMLCipher.WRAP_MODE, pubKey);

            encKey = cipher.encryptKey(doc, new SecretKeySpec(encryptedKey, "AES"));
            final KeyInfo keyinfo = new KeyInfo(doc);
            //KeyIdentifier keyIdentifier = new KeyIdentifierImpl(MessageConstants.ThumbPrintIdentifier_NS,null);
            //keyIdentifier.setValue(Base64.encode(X509ThumbPrintIdentifier.getThumbPrintIdentifier(serCert)));
            final KeyIdentifier keyIdentifier = new KeyIdentifierImpl(MessageConstants.X509SubjectKeyIdentifier_NS,null);
            keyIdentifier.setValue(Base64.encode(X509SubjectKeyIdentifier.getSubjectKeyIdentifier(cert)));
            final SecurityTokenReference str = new SecurityTokenReferenceImpl(keyIdentifier);
            keyinfo.addUnknownElement((Element)doc.importNode(WSTrustElementFactory.newInstance().toElement(str,null), true));
            encKey.setKeyInfo(keyinfo);
        } catch (XWSSecurityException ex){
            log.log(Level.SEVERE,
                            LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
            throw new WSTrustException( LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
        } catch (XMLEncryptionException ex) {
            log.log(Level.SEVERE,
                            LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
            throw new WSTrustException( LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
        }
        
        return encKey;
    
private org.w3c.dom.ElementencryptToken(org.w3c.dom.Element assertion, java.security.cert.X509Certificate serCert, java.lang.String appliesTo)

        Element encDataEle = null;
        // Create the encryption key
        try{
            final XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_256);
            final int keysizeInBytes = 32;
            final byte[] skey = WSTrustUtil.generateRandomSecret(keysizeInBytes);
            cipher.init(XMLCipher.ENCRYPT_MODE, new SecretKeySpec(skey, "AES"));
                
            // Encrypt the assertion and return the Encrypteddata
            final Document owner = assertion.getOwnerDocument();
            final EncryptedData encData = cipher.encryptData(owner, assertion);
            final String id = "uuid-" + UUID.randomUUID().toString();
            encData.setId(id);
                
            final KeyInfo encKeyInfo = new KeyInfo(owner);
            final EncryptedKey encKey = encryptKey(owner, skey, serCert, appliesTo);
            encKeyInfo.add(encKey);
            encData.setKeyInfo(encKeyInfo);
            
            encDataEle = cipher.martial(encData);
         } catch (XMLEncryptionException ex) {
            log.log(Level.SEVERE,
                            LogStringsMessages.WST_0044_ERROR_ENCRYPT_ISSUED_TOKEN(appliesTo), ex);
            throw new WSTrustException( LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
        } catch (Exception ex) {
            log.log(Level.SEVERE,
                            LogStringsMessages.WST_0044_ERROR_ENCRYPT_ISSUED_TOKEN(appliesTo), ex);
            throw new WSTrustException( LogStringsMessages.WST_0040_ERROR_ENCRYPT_PROOFKEY(appliesTo), ex);
        }
        
        
        return encDataEle;
    
private java.lang.Object[]getSTSCertAndPrivateKey()

        
        X509Certificate stsCert = null;
        PrivateKey stsPrivKey = null;
        CallbackHandler callbackHandler = stsConfig.getCallbackHandler();
        if (callbackHandler != null){
            final SignatureKeyCallback.DefaultPrivKeyCertRequest request =
                    new SignatureKeyCallback.DefaultPrivKeyCertRequest();
            final Callback skc = new SignatureKeyCallback(request);
            final Callback[] callbacks = {skc};
            try{
                callbackHandler.handle(callbacks);
            }catch(IOException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);            
            }catch(UnsupportedCallbackException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);
            }
                
            stsPrivKey = request.getPrivateKey();
            stsCert = request.getX509Certificate();
        }else{
            SecurityEnvironment secEnv = (SecurityEnvironment)stsConfig.getOtherOptions().get(WSTrustConstants.SECURITY_ENVIRONMENT);
            try{
                stsCert = secEnv.getDefaultCertificate(new HashMap());
                stsPrivKey = secEnv.getPrivateKey(new HashMap(), stsCert);
            }catch( XWSSecurityException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0043_UNABLE_GET_STS_KEY(), ex);
            }
        }
        
        Object[] results = new Object[2];
        results[0] = stsCert;
        results[1] = stsPrivKey;
        return results;
    
private java.security.cert.X509CertificategetServiceCertificate(com.sun.xml.ws.api.security.trust.config.TrustSPMetadata spMd, java.lang.String appliesTo)

        String certAlias = spMd.getCertAlias();
        X509Certificate cert = null;
        CallbackHandler callbackHandler = stsConfig.getCallbackHandler();
        if (callbackHandler != null){
            // Get the service certificate
            final EncryptionKeyCallback.AliasX509CertificateRequest req = new EncryptionKeyCallback.AliasX509CertificateRequest(spMd.getCertAlias());
            final EncryptionKeyCallback callback = new EncryptionKeyCallback(req);
            final Callback[] callbacks = {callback};
            try{
                callbackHandler.handle(callbacks);
            }catch(IOException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);            
            }catch(UnsupportedCallbackException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
            }
        
            cert = req.getX509Certificate();
        }else{
            SecurityEnvironment secEnv = (SecurityEnvironment)stsConfig.getOtherOptions().get(WSTrustConstants.SECURITY_ENVIRONMENT);
            try{
                cert = secEnv.getCertificate(new HashMap(), certAlias, false);
            }catch( XWSSecurityException ex){
                log.log(Level.SEVERE,
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
                throw new WSTrustException(
                    LogStringsMessages.WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
            }
        }
        
        return cert;