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

SBIssuedSamlTokenContractImpl

public class SBIssuedSamlTokenContractImpl extends IssueSamlTokenContract
author

Fields Summary
private static final String
SAML_HOLDER_OF_KEY
protected static final String
PRINCIPAL
private com.sun.xml.ws.api.SOAPVersion
soapVersion
com.sun.xml.ws.security.opt.impl.util.WSSElementFactory
wef
private static final Logger
log
Constructors Summary
public SBIssuedSamlTokenContractImpl(com.sun.xml.ws.api.SOAPVersion soapVersion)
Creates a new instance of SBIssuedSamlTokenContractImpl

    
           
       
        this.soapVersion = soapVersion;
    
public SBIssuedSamlTokenContractImpl()

        //constructor
    
Methods Summary
public com.sun.xml.security.core.xenc.EncryptedDataTypecreateEncryptedData(java.lang.String id, java.lang.String dataEncAlgo, com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.KeyInfo keyInfo, boolean contentOnly)

        final EncryptedDataType edt = new EncryptedDataType();
        if(contentOnly){
            edt.setType(MessageConstants.ENCRYPT_ELEMENT_CONTENT);
        }else{
            edt.setType(MessageConstants.ENCRYPT_ELEMENT);
        }
        final EncryptionMethodType emt = new EncryptionMethodType();
        emt.setAlgorithm(dataEncAlgo);
        edt.setEncryptionMethod(emt);
        final CipherDataType cipherType = new CipherDataType();
        cipherType.setCipherValue("ed".getBytes());
        edt.setCipherData(cipherType);
        edt.setId(id);
        if(keyInfo != null){
            edt.setKeyInfo(keyInfo);
        }
        return edt;
    
private com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.KeyInfocreateKeyInfo(java.lang.String keyType, java.security.cert.X509Certificate serCert, com.sun.xml.ws.security.IssuedTokenContext ctx)

        final KeyInfo keyInfo = new KeyInfo();
        if (WSTrustConstants.SYMMETRIC_KEY.equals(keyType)){
            final byte[] key = ctx.getProofKey();
            if (!stsConfig.getEncryptIssuedToken() && stsConfig.getEncryptIssuedKey()){
                try{
                    final Key secKey = new SecretKeySpec(key, "AES");
                    final EncryptedKey encKey = encryptKey(secKey, serCert);
                    keyInfo.getContent().add(encKey);
                }catch(Exception ex){
                    throw new WSTrustException(ex.getMessage(), ex);
                }
            }else{
                final BinarySecret secret = eleFac.createBinarySecret(key, BinarySecret.SYMMETRIC_KEY_TYPE);
                keyInfo.getContent().add(secret);
            }
        }else if(WSTrustConstants.PUBLIC_KEY.equals(keyType)){
            
            final X509Data x509Data = new X509Data();
            final Set certs = ctx.getRequestorSubject().getPublicCredentials();
            if(certs == null){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
                throw new WSTrustException(LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
            }
            boolean addedClientCert = false;
            final ObjectFactory dsigOF = new ObjectFactory();
            for(Object o : certs){
                if(o instanceof X509Certificate){
                    final X509Certificate clientCert = (X509Certificate)o;
                    
                    JAXBElement<byte[]> certElement;
                    try {
                        certElement = dsigOF.createX509DataTypeX509Certificate(clientCert.getEncoded());
                    } catch (CertificateEncodingException ex) {
                        //ex.printStackTrace();
                        throw new WSTrustException("Unable to create KeyInfo",ex);
                    }
                    x509Data.getContent().add(certElement);
                    addedClientCert = true;
                    
                }
            }
            if(!addedClientCert){
                log.log(Level.SEVERE,
                        LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
                throw new WSTrustException(LogStringsMessages.WST_0034_UNABLE_GET_CLIENT_CERT());
            }
            keyInfo.getContent().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.xml.ws.security.opt.crypto.dsig.keyinfo.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);
            
            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 AttributeStatement statement = samlFac.createAttributeStatement(subj, attrs);
            final List<AttributeStatement> statements = new ArrayList<AttributeStatement>();
            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.xml.ws.security.opt.crypto.dsig.keyinfo.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
            
            final SubjectConfirmationData subjComfData = samlFac.createSubjectConfirmationData(
                    null, null, issueInst, notOnOrAfter, appliesTo, keyInfo);
            
            final SubjectConfirmation subConfirmation = samlFac.createSubjectConfirmation(
                    null, subjComfData, 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 NameIdentifier nameId = samlFac.createNameIdentifier(values.get(0), attrKey.getNamespaceURI(), null);
                        subj = samlFac.createSubject(nameId, subConfirmation);
                    }
                    else{
                        final Attribute attr = samlFac.createAttribute(attrKey.getLocalPart(), values);
                        attrs.add(attr);
                    }
                }
            }
            final AttributeStatement statement = samlFac.createAttributeStatement(attrs);
            final List<AttributeStatement> statements = new ArrayList<AttributeStatement>();
            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;
        
        final CallbackHandler callbackHandler = stsConfig.getCallbackHandler();
        
        try{
            NamespaceContextEx nsContext = null;
            if(soapVersion == soapVersion.SOAP_11){
                nsContext = new NamespaceContextEx();
            }else{
                nsContext  = new NamespaceContextEx(true);
            }
            nsContext.addEncryptionNS();
            nsContext.addExc14NS();
            nsContext.addSAMLNS();
            nsContext.addSignatureNS();
            nsContext.addWSSNS();
            // Get the service certificate
            final X509Certificate serCert = getServiceCertificate(callbackHandler, stsConfig.getTrustSPMetadata(appliesTo), appliesTo);
            
            // Create the KeyInfo for SubjectConfirmation
            final KeyInfo keyInfo = createKeyInfo(keyType, serCert, context);
            
            // Create SAML assertion
            Assertion assertion = null;
            SAMLToken samlToken = null;
            if (WSTrustConstants.SAML10_ASSERTION_TOKEN_TYPE.equals(tokenType)||
                    WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE.equals(tokenType)){
                assertion = createSAML11Assertion(assertionId, issuer, appliesTo, keyInfo, claimedAttrs);
                samlToken = new SAMLToken(assertion,SAMLJAXBUtil.getJAXBContext(),soapVersion);
                
            } else if (WSTrustConstants.SAML20_ASSERTION_TOKEN_TYPE.equals(tokenType)){
                assertion = createSAML20Assertion(assertionId, issuer, appliesTo, keyInfo, claimedAttrs);
                samlToken = new SAMLToken(assertion,SAMLJAXBUtil.getJAXBContext(),soapVersion);
            } 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 public and private key
            final SignatureKeyCallback.DefaultPrivKeyCertRequest request =
                    new SignatureKeyCallback.DefaultPrivKeyCertRequest();
            final Callback skc = new SignatureKeyCallback(request);
            final Callback[] callbacks = {skc};
            callbackHandler.handle(callbacks);
            final PrivateKey stsPrivKey = request.getPrivateKey();
            
            // Sign the assertion with STS's private key
            //Element signedAssertion = assertion.sign(request.getX509Certificate(), stsPrivKey);
            final SecurityHeaderElement signedAssertion = createSignature(request.getX509Certificate().getPublicKey(),stsPrivKey,samlToken,nsContext);
            
            //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()){
                final String id = "uuid-" + UUID.randomUUID().toString();
                final int keysizeInBytes = 32;
                final byte[] skey = WSTrustUtil.generateRandomSecret(keysizeInBytes);
                final Key key = new SecretKeySpec(skey, "AES");
                
                final KeyInfo encKeyInfo = new KeyInfo();
                final EncryptedKey encKey = encryptKey(key, serCert);
                encKeyInfo.getContent().add(encKey);
                final EncryptedDataType edt = createEncryptedData(id,MessageConstants.AES_BLOCK_ENCRYPTION_256,encKeyInfo,false);
                
                
                final JAXBEncryptedData jed = new JAXBEncryptedData(edt,new SSEData((SecurityElement)signedAssertion,false,nsContext),soapVersion);
                token = new GenericToken(jed);
            }else{
                token = new GenericToken(signedAssertion);
            }
        } 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);
        }catch (Exception 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 token;
    
private com.sun.xml.ws.security.opt.api.SecurityHeaderElementcreateSignature(java.security.PublicKey pubKey, java.security.Key signingKey, com.sun.xml.ws.security.opt.impl.keyinfo.SAMLToken samlToken, com.sun.xml.ws.security.opt.impl.util.NamespaceContextEx nsContext)

        try{
            final JAXBSignatureFactory signatureFactory = JAXBSignatureFactory.newInstance();
            final C14NMethodParameterSpec spec = null;
            final CanonicalizationMethod canonicalMethod =
                    signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,spec);
            DigestMethod digestMethod;
            digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null);
            SignatureMethod signatureMethod;
            signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            
            //Note : Signature algorithm parameters null for now , fix me.
            
            final ArrayList<Transform> transformList = new ArrayList<Transform>();
            Transform tr1;
            
            tr1 = signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
            
            Transform tr2;
            
            tr2 = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);
            
            transformList.add(tr1);
            transformList.add(tr2);
            
            final String uri = "#" + "uuid-" + UUID.randomUUID().toString();
            final Reference ref = signatureFactory.newReference(uri,digestMethod,transformList, null, null);
            
            // Create the SignedInfo
            final SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalMethod,signatureMethod,Collections.singletonList(ref));
            
            KeyValue keyValue;
            
            //kv = kif.newKeyValue(pubKey);
            if (pubKey instanceof java.security.interfaces.DSAPublicKey) {
                DSAKeyValue dsa = null;
                final DSAPublicKey key = (DSAPublicKey)pubKey;
                
                final byte[] paramP = key.getParams().getP().toByteArray();
                final byte[] paramQ = key.getParams().getQ().toByteArray();
                final byte[] paramG = key.getParams().getG().toByteArray();
                final byte[] paramY = key.getY().toByteArray();
                dsa = signatureFactory.newDSAKeyValue(paramP,paramQ,paramG,paramY,null,null,null);
                keyValue = signatureFactory.newKeyValue(Collections.singletonList(dsa));
                
            } else if (pubKey instanceof java.security.interfaces.RSAPublicKey) {
                RSAKeyValue rsa = null;
                final RSAPublicKey key = (RSAPublicKey)pubKey;
                rsa = signatureFactory.newRSAKeyValue(key.getModulus().toByteArray(),key.getPublicExponent().toByteArray());
                keyValue = signatureFactory.newKeyValue(Collections.singletonList(rsa));
            }else{
                throw new WSTrustException("Unsupported PublicKey");
            }
            
            // Create a KeyInfo and add the KeyValue to it
            final javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = signatureFactory.newKeyInfo(Collections.singletonList(keyValue));
            final JAXBSignContext signContext = new JAXBSignContext(signingKey);
            
            final SSEData data = null;
            signContext.setURIDereferencer(new DSigResolver(data));
            final com.sun.xml.ws.security.opt.crypto.dsig.Signature signature = (Signature) signatureFactory.newXMLSignature(signedInfo,keyInfo);
            final JAXBSignatureHeaderElement jhe =  new JAXBSignatureHeaderElement(signature,soapVersion,(XMLSignContext)signContext);
            return new EnvelopedSignedMessageHeader(samlToken,(com.sun.xml.ws.security.opt.crypto.dsig.Reference) ref, jhe,nsContext);
//        } catch (KeyException ex) {
//            ex.printStackTrace();
//            throw new WSTrustException("Unable to create sign SAML Assertion",ex);
//        }
        } catch (NoSuchAlgorithmException ex) {
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
            throw new WSTrustException(LogStringsMessages.WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(),ex);
        } catch (InvalidAlgorithmParameterException ex) {
            log.log(Level.SEVERE,
                    LogStringsMessages.WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
            throw new WSTrustException(LogStringsMessages.WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(),ex);
        }
    
private com.sun.xml.ws.security.opt.api.EncryptedKeyencryptKey(java.security.Key key, java.security.cert.X509Certificate cert)

        KeyInfo keyInfo = null;
        final KeyIdentifier keyIdentifier = wef.createKeyIdentifier();
        keyIdentifier.setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
        keyIdentifier.updateReferenceValue(cert);
        keyIdentifier.setEncodingType(MessageConstants.BASE64_ENCODING_NS);
        final SecurityTokenReference str = wef.createSecurityTokenReference(keyIdentifier);
        keyInfo = wef.createKeyInfo((com.sun.xml.ws.security.opt.impl.keyinfo.SecurityTokenReference) str);
        
        return wef.createEncryptedKey(null,MessageConstants.RSA_OAEP_KEY_TRANSPORT,keyInfo,cert.getPublicKey(),key);
    
private java.security.cert.X509CertificategetServiceCertificate(javax.security.auth.callback.CallbackHandler callbackHandler, com.sun.xml.ws.api.security.trust.config.TrustSPMetadata spMd, java.lang.String appliesTo)

        // 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);
        }
        
        return req.getX509Certificate();