Package org.apache.rahas

Examples of org.apache.rahas.TrustException


        data.setEphmeralKey(tempKey);

        // Extract the Encryptedkey DOM element
        encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
      } catch (WSSecurityException e) {
        throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal",
            new String[]{serviceCert.getSubjectDN().getName()}, e);
      }

      keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
      ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS,
          WSConstants.SIG_PREFIX);
      ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS,
          WSConstants.ENC_PREFIX);

      keyInfoElem.appendChild(encryptedKeyElem);

    }

    // If it is a public Key
    else {
      try {
        String subjectNameId = data.getPrincipal().getName();

        // Create NameID and attach it to the subject
        NameIDBuilder nb = new NameIDBuilder();
        NameID nameID = nb.buildObject();
        nameID.setValue(subjectNameId);
        nameID.setFormat(NameIdentifier.EMAIL);
        subject.setNameID(nameID);

        // Create the ds:KeyValue element with the ds:X509Data
        X509Certificate clientCert = data.getClientCert();

        if (clientCert == null) {
          X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName());
          clientCert = certs[0];
        }

        byte[] clientCertBytes = clientCert.getEncoded();

        String base64Cert = Base64.encode(clientCertBytes);

        Text base64CertText = doc.createTextNode(base64Cert);

        // -----------------------------------------

        Element x509CertElem = doc
            .createElementNS(WSConstants.SIG_NS, "ds:X509Certificate");
        x509CertElem.appendChild(base64CertText);
        Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Data");
        x509DataElem.appendChild(x509CertElem);

        if (x509DataElem != null) {
          keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
          ((OMElement) x509DataElem).declareNamespace(WSConstants.SIG_NS,
              WSConstants.SIG_PREFIX);
          ((OMElement) x509DataElem).declareNamespace(WSConstants.ENC_NS,
              WSConstants.ENC_PREFIX);

          keyInfoElem.appendChild(x509DataElem);
        }

      } catch (Exception e) {
        throw new TrustException("samlAssertionCreationError", e);
      }
    }

    // Unmarshall the keyInfo DOM element into an XMLObject
    String keyInfoElementString = keyInfoElem.toString();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim()
        .getBytes()));
    Element element = document.getDocumentElement();

    // Get appropriate unmarshaller
    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);

    // Unmarshall using the document root element, an keyInfo element in this case
    XMLObject keyInfoElement = null;
    try {
      keyInfoElement = unmarshaller.unmarshall(element);
    } catch (UnmarshallingException e) {
      throw new TrustException("Error unmarshalling KeyInfo Element", e);
    }

    // Build the Subject Confirmation
    SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) builderFactory
        .getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
View Full Code Here


      Marshaller marshaller = marshallerFactory.getMarshaller(assertion);
      marshaller.marshall(assertion);
      org.apache.xml.security.Init.init();
      Signer.signObjects(signatureList);
    } catch (CertificateEncodingException e) {
      throw new TrustException("Error in setting the signature", e);
    } catch (SignatureException e) {
      throw new TrustException("errorMarshellingOrSigning", e);
    } catch (MarshallingException e) {
      throw new TrustException("errorMarshellingOrSigning", e);
    }

    if (log.isDebugEnabled()) {
      log.debug("SAML2.0 assertion is marshalled and signed..");
    }
View Full Code Here

   */
  protected static XMLObject buildXMLObject(QName objectQName) throws Exception {
    XMLObjectBuilder builder = org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(
        objectQName);
    if (builder == null) {
      throw new TrustException("Unable to retrieve builder for object QName " + objectQName);
    }
    return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
        objectQName.getPrefix());
  }
View Full Code Here

      signKeyHolder.setIssuerCerts(issuerCerts);
      signKeyHolder.setIssuerPK((PrivateKey) issuerPK);
      signKeyHolder.setSignatureAlgorithm(sigAlgo);

    } catch (Exception e) {
      throw new TrustException("Error creating issuer signature");
    }

    if (log.isDebugEnabled()) {
      log.debug("SignKeyHolder object is created with the credentials..");
    }
View Full Code Here

      ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
      Class cbClass = null;
      try {
        cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
      } catch (ClassNotFoundException e) {
        throw new TrustException("cannotLoadPWCBClass", new String[]{config
            .getCallbackHandlerName()}, e);
      }
      try {
        handler = (SAMLCallbackHandler) cbClass.newInstance();
      } catch (java.lang.Exception e) {
        throw new TrustException("cannotCreatePWCBInstance", new String[]{config
            .getCallbackHandlerName()}, e);
      }
      handler.handle(cb);
      attributes = cb.getSAML2Attributes();
      // else add the attribute with a default value
View Full Code Here

                log.debug("DOM element is created successfully from the OpenSAML2 XMLObject");
            }
            return assertionElement;

        } catch (Exception e) {
            throw new TrustException("Error creating DOM object from the assertion", e);
        }
    }
View Full Code Here

                if (param != null && param.getParameterElement() != null) {
                    config = new SAMLTokenIssuerConfig(param
                            .getParameterElement().getFirstChildWithName(
                                    SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
                } else {
                    throw new TrustException("expectedParameterMissing",
                            new String[] { this.configParamName });
                }
            }

            if (config == null) {
                throw new TrustException("configurationIsNull");
            }

            // Set the DOM impl to DOOM
            DocumentBuilderFactoryImpl.setDOOMRequired(true);

            SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
                    .getEnvelope().getNamespace().getNamespaceURI());

            Crypto crypto;
            if (config.cryptoElement != null) { // crypto props
                                                            // defined as
                                                            // elements
                crypto = CryptoFactory.getInstance(TrustUtil
                        .toProperties(config.cryptoElement), inMsgCtx
                        .getAxisService().getClassLoader());
            } else { // crypto props defined in a properties file
                crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
                        inMsgCtx.getAxisService().getClassLoader());
            }

            // Creation and expiration times
            Date creationTime = new Date();
            Date expirationTime = new Date();
            expirationTime.setTime(creationTime.getTime() + config.ttl);

            // Get the document
            Document doc = ((Element) env).getOwnerDocument();

            // Get the key size and create a new byte array of that size
            int keySize = data.getKeysize();

            keySize = (keySize == -1) ? config.keySize : keySize;

            /*
             * Find the KeyType If the KeyType is SymmetricKey or PublicKey,
             * issue a SAML HoK assertion. - In the case of the PublicKey, in
             * coming security header MUST contain a certificate (maybe via
             * signature)
             *
             * If the KeyType is Bearer then issue a Bearer assertion
             *
             * If the key type is missing we will issue a HoK assertion
             */

            String keyType = data.getKeyType();
            SAMLAssertion assertion;
            if (keyType == null) {
                throw new TrustException(TrustException.INVALID_REQUEST,
                        new String[] { "Requested KeyType is missing" });
            }

            if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                    || keyType.endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
                assertion = createHoKAssertion(config, doc, crypto,
                        creationTime, expirationTime, data);
            } else if (keyType.endsWith(RahasConstants.KEY_TYPE_BEARER)) {
                assertion = createBearerAssertion(config, doc, crypto,
                        creationTime, expirationTime, data);
            } else {
                throw new TrustException("unsupportedKeyType");
            }

            OMElement rstrElem;
            int wstVersion = data.getVersion();
            if (RahasConstants.VERSION_05_02 == wstVersion) {
                rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
                        wstVersion, env.getBody());
            } else {
                OMElement rstrcElem = TrustUtil
                        .createRequestSecurityTokenResponseCollectionElement(
                                wstVersion, env.getBody());
                rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
                        wstVersion, rstrcElem);
            }

            TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
                    RahasConstants.TOK_TYPE_SAML_10);

            if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
                TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
            }

            if (config.addRequestedAttachedRef) {
              TrustUtil.createRequestedAttachedRef(rstrElem, assertion.getId(),wstVersion);
            }

            if (config.addRequestedUnattachedRef) {
              TrustUtil.createRequestedUnattachedRef(rstrElem, assertion.getId(),wstVersion);  
            }

            if (data.getAppliesToAddress() != null) {
                TrustUtil.createAppliesToElement(rstrElem, data
                        .getAppliesToAddress(), data.getAddressingNs());
            }

            // Use GMT time in milliseconds
            DateFormat zulu = new XmlSchemaDateFormat();

            // Add the Lifetime element
            TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
                    .format(creationTime), zulu.format(expirationTime));

            // Create the RequestedSecurityToken element and add the SAML token
            // to it
            OMElement reqSecTokenElem = TrustUtil
                    .createRequestedSecurityTokenElement(wstVersion, rstrElem);
            Token assertionToken;
            try {
                Node tempNode = assertion.toDOM();
                reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
                        .getOwnerDocument().importNode(tempNode, true));

                // Store the token
                assertionToken = new Token(assertion.getId(),
                        (OMElement) assertion.toDOM(), creationTime,
                        expirationTime);

                // At this point we definitely have the secret
                // Otherwise it should fail with an exception earlier
                assertionToken.setSecret(data.getEphmeralKey());
                TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);

            } catch (SAMLException e) {
                throw new TrustException("samlConverstionError", e);
            }

            if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                    && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {

View Full Code Here

             
                return createAuthAssertion(doc, SAMLSubject.CONF_BEARER,
                        nameId, null, config, crypto, creationTime,
                        expirationTime);
            } else {
                throw new TrustException("samlUnsupportedPrincipal",
                        new String[] { principal.getClass().getName() });
            }
        } catch (SAMLException e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }
View Full Code Here

                data.setEphmeralKey(tempKey);

                // Extract the Encryptedkey DOM element
                encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
            } catch (WSSecurityException e) {
                throw new TrustException(
                        "errorInBuildingTheEncryptedKeyForPrincipal",
                        new String[] { serviceCert.getSubjectDN().getName() },
                        e);
            }
            return this.createAttributeAssertion(doc, data ,encryptedKeyElem, config,
                    crypto, creationTime, expirationTime);
        } else {
            try {
                String subjectNameId = data.getPrincipal().getName();
               
                SAMLNameIdentifier nameId = new SAMLNameIdentifier(
                        subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL);

                // Create the ds:KeyValue element with the ds:X509Data
                X509Certificate clientCert = data.getClientCert();

                if(clientCert == null) {
                    X509Certificate[] certs = crypto.getCertificates(
                            data.getPrincipal().getName());
                    clientCert = certs[0];
                }

                byte[] clientCertBytes = clientCert.getEncoded();

                String base64Cert = Base64.encode(clientCertBytes);

                Text base64CertText = doc.createTextNode(base64Cert);
                Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS,
                        "X509Certificate");
                x509CertElem.appendChild(base64CertText);
                Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS,
                        "X509Data");
                x509DataElem.appendChild(x509CertElem);

                return this.createAuthAssertion(doc,
                        SAMLSubject.CONF_HOLDER_KEY, nameId, x509DataElem,
                        config, crypto, creationTime, expirationTime);
            } catch (Exception e) {
                throw new TrustException("samlAssertionCreationError", e);
            }
        }
    }
View Full Code Here

        ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
        Class cbClass = null;
        try {
          cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
        } catch (ClassNotFoundException e) {
          throw new TrustException("cannotLoadPWCBClass", new String[]{config
              .getCallbackHandlerName()}, e);
        }
        try {
          handler = (SAMLCallbackHandler) cbClass.newInstance();
        } catch (java.lang.Exception e) {
          throw new TrustException("cannotCreatePWCBInstance", new String[]{config
              .getCallbackHandlerName()}, e);
        }
        handler.handle(cb);
        attrs = cb.getAttributes();
            }else{
              //TODO Remove this after discussing
                SAMLAttribute attribute = new SAMLAttribute("Name",
                        "https://rahas.apache.org/saml/attrns", null, -1, Arrays
                                .asList(new String[] { "Colombo/Rahas" }));
                attrs = new SAMLAttribute[]{attribute};
            }
           
            SAMLAttributeStatement attrStmt = new SAMLAttributeStatement(
            subject, Arrays.asList(attrs ));

            SAMLStatement[] statements = { attrStmt };

            SAMLAssertion assertion = new SAMLAssertion(config.issuerName,
                    notBefore, notAfter, null, null, Arrays.asList(statements));

            // sign the assertion
            X509Certificate[] issuerCerts = crypto
                    .getCertificates(config.issuerKeyAlias);

            String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
            String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
            if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
                sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
            }
            java.security.Key issuerPK = crypto.getPrivateKey(
                    config.issuerKeyAlias, config.issuerKeyPassword);
            assertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));

            return assertion;
        } catch (Exception e) {
            throw new TrustException("samlAssertionCreationError", e);
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.rahas.TrustException

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.