Java Code Examples for org.keycloak.saml.common.exceptions.ProcessingException

The following examples show how to use org.keycloak.saml.common.exceptions.ProcessingException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
protected Response buildAuthenticatedResponse(AuthenticatedClientSessionModel clientSession, String redirectUri, Document samlDocument, JaxrsSAML2BindingBuilder bindingBuilder) throws ConfigurationException, ProcessingException, IOException {

//        // TODO use Keycloak provider information from this.session
//        Element assertionElement = (Element) samlDocument.getElementsByTagNameNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "Assertion").item(0);
//
//        Element attributeStatementElement = (Element) assertionElement.getElementsByTagNameNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "AttributeStatement").item(0);
//        if (attributeStatementElement == null) {
//            attributeStatementElement = samlDocument.createElementNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "AttributeStatement");
//            assertionElement.appendChild(attributeStatementElement);
//        }
//        // TODO pull information from user attributes
//        attributeStatementElement.appendChild(newSamlAttributeElement(samlDocument, null, "Role", JBossSAMLURIConstants.ATTRIBUTE_FORMAT_BASIC.get(), "dummy", "xsd:string"));

//        // see: http://oid-info.com/get/
//        attributeStatementElement.appendChild(newSamlAttributeElement(samlDocument, "XSPA Organization ID", "urn:oasis:names:tc:xspa:1.0:subject:organization-id", JBossSAMLURIConstants.ATTRIBUTE_FORMAT_URI.get(), "urn:oid:1.2.3.4.5.6.7.8.9.10.11.12", "xsd:anyURI"));
//
//        Element roleElement = samlDocument.createElementNS("urn:hl7-org:v3", "Role");
//        roleElement.setAttribute("code", "PRA");
//        roleElement.setAttribute("codeSystem", "1.2.3.4.5.6.7.8.9.10.11.12");
//        roleElement.setAttribute("codeSystemName", "IHEXDShealthcareFacilityTypeCode");
//        roleElement.setAttribute("displayName", "Doctor's office");
//        attributeStatementElement.appendChild(newSamlAttributeElement(samlDocument, "Acme Role", "urn:oasis:names:tc:xacml:2.0:subject:role", JBossSAMLURIConstants.ATTRIBUTE_FORMAT_URI.get(), roleElement, "xsd:anyType"));

        return super.buildAuthenticatedResponse(clientSession, redirectUri, samlDocument, bindingBuilder);
    }
 
Example 2
Source Project: keycloak   Source File: SamlClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest createSamlSignedResponse(URI samlEndpoint, String relayState, Document samlRequest, String realmPrivateKey, String realmPublicKey) {

    try {
        BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder();

        if (realmPrivateKey != null && realmPublicKey != null) {
            PrivateKey privateKey = org.keycloak.testsuite.util.KeyUtils.privateKeyFromString(realmPrivateKey);
            PublicKey publicKey = org.keycloak.testsuite.util.KeyUtils.publicKeyFromString(realmPublicKey);
            binding
                    .signatureAlgorithm(SignatureAlgorithm.RSA_SHA256)
                    .signWith(KeyUtils.createKeyId(privateKey), privateKey, publicKey)
                    .signDocument();
        }

        binding.relayState(relayState);

        return new HttpGet(binding.redirectBinding(samlRequest).responseURI(samlEndpoint.toString()));
    } catch (IOException | ConfigurationException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 3
Source Project: keycloak   Source File: SamlClient.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HttpUriRequest createSamlSignedRequest(URI samlEndpoint, String relayState, Document samlRequest, String privateKeyStr, String publicKeyStr) {
    try {
        BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder().relayState(relayState);
        if (privateKeyStr != null && publicKeyStr != null) {
            PrivateKey privateKey = org.keycloak.testsuite.util.KeyUtils.privateKeyFromString(privateKeyStr);
            PublicKey publicKey = org.keycloak.testsuite.util.KeyUtils.publicKeyFromString(publicKeyStr);
            binding.signatureAlgorithm(SignatureAlgorithm.RSA_SHA256)
                    .signWith(KeyUtils.createKeyId(privateKey), privateKey, publicKey)
                    .signDocument();
        }
        return new HttpGet(binding.redirectBinding(samlRequest).requestURI(samlEndpoint.toString()));
    } catch (IOException | ConfigurationException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 4
Source Project: keycloak   Source File: BrokerTest.java    License: Apache License 2.0 6 votes vote down vote up
private SAML2Object createAuthnResponse(SAML2Object so) {
    AuthnRequestType req = (AuthnRequestType) so;
    try {
        final ResponseType res = new SAML2LoginResponseBuilder()
          .requestID(req.getID())
          .destination(req.getAssertionConsumerServiceURL().toString())
          .issuer("https://saml.idp/saml")
          .assertionExpiration(1000000)
          .subjectExpiration(1000000)
          .requestIssuer(getAuthServerRealmBase(REALM_NAME).toString())
          .sessionIndex("idp:" + UUID.randomUUID())
          .buildModel();

        AttributeStatementType attrStatement = new AttributeStatementType();
        AttributeType attribute = new AttributeType("mail");
        attribute.addAttributeValue("[email protected]");
        attrStatement.addAttribute(new ASTChoiceType(attribute));

        res.getAssertions().get(0).getAssertion().addStatement(attrStatement);

        return res;
    } catch (ConfigurationException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 5
Source Project: keycloak   Source File: BrokerTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void signAndAddCustomNamespaceElementToSignature(Document doc) {
    doc.getDocumentElement().setAttribute("xmlns:" + XMLNS_VETINARI, NS_VETINARI);

    BaseSAML2BindingBuilder<BaseSAML2BindingBuilder> sb = new BaseSAML2BindingBuilder();
    try {
        KeyPair keyPair = new KeyPair(SAML_CLIENT_SALES_POST_SIG_PUBLIC_KEY_PK, SAML_CLIENT_SALES_POST_SIG_PRIVATE_KEY_PK);
        sb.signWith("kn", keyPair)
          .signatureAlgorithm(RSA_SHA1)
          .signAssertions()
          .signAssertion(doc);
    } catch (ProcessingException ex) {
        throw new RuntimeException(ex);
    }

    // KeyInfo has lax and can contain custom elements, see https://www.w3.org/TR/xmldsig-core1/#sec-KeyInfo
    Element el = findFirstElement(doc, XmlDSigQNames.KEY_INFO);
    appendNewElement(el, new QName(NS_VETINARI, "Patrician"), XMLNS_VETINARI);
}
 
Example 6
Source Project: keycloak   Source File: BaseWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void write(ExtensionsType extensions) throws ProcessingException {
    if (extensions.getAny().isEmpty()) {
        return;
    }

    StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.EXTENSIONS__PROTOCOL.get(), PROTOCOL_NSURI.get());

    for (Object o : extensions.getAny()) {
        if (o instanceof Node) {
            StaxUtil.writeDOMNode(writer, (Node) o);
        } else if (o instanceof SamlProtocolExtensionsAwareBuilder.NodeGenerator) {
            SamlProtocolExtensionsAwareBuilder.NodeGenerator ng = (SamlProtocolExtensionsAwareBuilder.NodeGenerator) o;
            ng.write(writer);
        } else {
            throw logger.samlExtensionUnknownChild(o == null ? null : o.getClass());
        }
    }

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 7
Source Project: keycloak   Source File: TokenEndpoint.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Response buildAuthenticatedResponse(AuthenticatedClientSessionModel clientSession, String redirectUri,
                                              Document samlDocument, JaxrsSAML2BindingBuilder bindingBuilder)
        throws ConfigurationException, ProcessingException, IOException {
    JaxrsSAML2BindingBuilder.PostBindingBuilder builder = bindingBuilder.postBinding(samlDocument);

    Element assertionElement;
    if (samlClient.requiresEncryption()) {
        assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ENCRYPTED_ASSERTION.get()));
    } else {
        assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    }
    if (assertionElement == null) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    String assertion = DocumentUtil.getNodeAsString(assertionElement);
    return Response.ok(assertion, MediaType.APPLICATION_XML_TYPE).build();
}
 
Example 8
Source Project: keycloak   Source File: SamlUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void sendSaml(boolean asRequest, HttpFacade httpFacade, String actionUrl,
                        BaseSAML2BindingBuilder binding, Document document,
                        SamlDeployment.Binding samlBinding) throws ProcessingException, ConfigurationException, IOException {
    if (samlBinding == SamlDeployment.Binding.POST) {
        String html = asRequest ? binding.postBinding(document).getHtmlRequest(actionUrl) : binding.postBinding(document).getHtmlResponse(actionUrl) ;
        httpFacade.getResponse().setStatus(200);
        httpFacade.getResponse().setHeader("Content-Type", "text/html");
        httpFacade.getResponse().setHeader("Pragma", "no-cache");
        httpFacade.getResponse().setHeader("Cache-Control", "no-cache, no-store");
        httpFacade.getResponse().getOutputStream().write(html.getBytes(GeneralConstants.SAML_CHARSET));
        httpFacade.getResponse().end();
    } else {
        String uri = asRequest ? binding.redirectBinding(document).requestURI(actionUrl).toString() : binding.redirectBinding(document).responseURI(actionUrl).toString();
        httpFacade.getResponse().setStatus(302);
        httpFacade.getResponse().setHeader("Location", uri);
        httpFacade.getResponse().end();
    }
}
 
Example 9
protected AbstractInitiateLogin createChallenge() {
    return new AbstractInitiateLogin(deployment, sessionStore) {
        @Override
        protected void sendAuthnRequest(HttpFacade httpFacade, SAML2AuthnRequestBuilder authnRequestBuilder, BaseSAML2BindingBuilder binding) throws ProcessingException, ConfigurationException, IOException {
            if (isAutodetectedBearerOnly(httpFacade.getRequest())) {
                httpFacade.getResponse().setStatus(401);
                httpFacade.getResponse().end();
            }
            else {
                Document document = authnRequestBuilder.toDocument();
                SamlDeployment.Binding samlBinding = deployment.getIDP().getSingleSignOnService().getRequestBinding();
                SamlUtil.sendSaml(true, httpFacade, deployment.getIDP().getSingleSignOnService().getRequestBindingUrl(), binding, document, samlBinding);
            }
        }
    };
}
 
Example 10
Source Project: keycloak   Source File: SAML2Response.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Convert a SAML2 Response into a Document
 *
 * @param responseType
 *
 * @return
 *
 * @throws ParsingException
 * @throws ConfigurationException
 * @throws ProcessingException
 */
public Document convert(StatusResponseType responseType) throws ProcessingException, ConfigurationException,
        ParsingException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    SAMLResponseWriter writer = new SAMLResponseWriter(StaxUtil.getXMLStreamWriter(bos));

    if (responseType instanceof ResponseType) {
        ResponseType response = (ResponseType) responseType;
        writer.write(response);
    } else {
        writer.write(responseType, new QName(PROTOCOL_NSURI.get(), JBossSAMLConstants.LOGOUT_RESPONSE.get(), "samlp"));
    }

    return DocumentUtil.getDocument(new ByteArrayInputStream(bos.toByteArray()));
}
 
Example 11
Source Project: keycloak   Source File: BaseSAML2BindingBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public void encryptDocument(Document samlDocument) throws ProcessingException {
    String samlNSPrefix = getSAMLNSPrefix(samlDocument);

    try {
        QName encryptedAssertionElementQName = new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(),
                JBossSAMLConstants.ENCRYPTED_ASSERTION.get(), samlNSPrefix);

        byte[] secret = RandomSecret.createRandomSecret(encryptionKeySize / 8);
        SecretKey secretKey = new SecretKeySpec(secret, encryptionAlgorithm);

        // encrypt the Assertion element and replace it with a EncryptedAssertion element.
        XMLEncryptionUtil.encryptElement(new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(),
                        JBossSAMLConstants.ASSERTION.get(), samlNSPrefix), samlDocument, encryptionPublicKey,
                secretKey, encryptionKeySize, encryptedAssertionElementQName, true);
    } catch (Exception e) {
        throw new ProcessingException("failed to encrypt", e);
    }

}
 
Example 12
Source Project: keycloak   Source File: SAML11AssertionWriter.java    License: Apache License 2.0 6 votes vote down vote up
public void write(SAML11AttributeStatementType statement) throws ProcessingException {
    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.ATTRIBUTE_STATEMENT.get(),
            SAML11Constants.ASSERTION_11_NSURI);

    SAML11SubjectType subject = statement.getSubject();
    if (subject != null)
        write(subject);

    List<SAML11AttributeType> attributes = statement.get();
    if (attributes != null) {
        for (SAML11AttributeType attr : attributes) {
            write(attr);
        }
    }

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 13
Source Project: keycloak   Source File: BaseSAML2BindingBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null) return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;

    try {
        temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    }

    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);

    signDocument(temporaryDocument);

    samlDocument.adoptNode(clonedAssertionElement);

    Element parentNode = (Element) originalAssertionElement.getParentNode();

    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
}
 
Example 14
Source Project: keycloak   Source File: SAMLResponseWriter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Write a {@code StatusType} to stream
 *
 * @param status
 * @param out
 *
 * @throws ProcessingException
 */
public void write(StatusType status) throws ProcessingException {
    StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get());

    StatusCodeType statusCodeType = status.getStatusCode();
    write(statusCodeType);

    String statusMessage = status.getStatusMessage();
    if (StringUtil.isNotNull(statusMessage)) {
        StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS_MESSAGE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get());
        StaxUtil.writeEndElement(writer);
    }

    StatusDetailType statusDetail = status.getStatusDetail();
    if (statusDetail != null)
        write(statusDetail);

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 15
Source Project: keycloak   Source File: SamlSPFacade.java    License: Apache License 2.0 5 votes vote down vote up
private URI getSamlAuthnRequest(HttpServletRequest req) {
    try {
        BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder();
        SAML2Request samlReq = new SAML2Request();
        String appServerUrl = ServletTestUtils.getUrlBase(req) + "/employee/";
        String authServerUrl = ServletTestUtils.getAuthServerUrlBase() + "/auth/realms/demo/protocol/saml";
        AuthnRequestType loginReq;
        loginReq = samlReq.createAuthnRequestType(UUID.randomUUID().toString(), appServerUrl, authServerUrl, "http://localhost:8280/employee/");
        loginReq.getNameIDPolicy().setFormat(JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.getUri());

        return binding.redirectBinding(SAML2Request.convert(loginReq)).requestURI(authServerUrl);
    } catch (IOException | ConfigurationException | ParsingException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 16
Source Project: keycloak   Source File: CreateAuthnRequestStepBuilder.java    License: Apache License 2.0 5 votes vote down vote up
protected Document createLoginRequestDocument() {
    if (this.forceLoginRequestDocument != null) {
        return this.forceLoginRequestDocument;
    }

    try {
        SAML2Request samlReq = new SAML2Request();
        AuthnRequestType loginReq = samlReq.createAuthnRequestType(UUID.randomUUID().toString(),
                assertionConsumerURL, this.authServerSamlUrl.toString(), issuer, requestBinding.getBindingUri());

        return SAML2Request.convert(loginReq);
    } catch (ConfigurationException | ParsingException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 17
Source Project: keycloak   Source File: XMLEncryptionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Encrypt the Key to be transported
 * </p>
 * <p>
 * Data is encrypted with a SecretKey. Then the key needs to be transported to the other end where it is needed for
 * decryption. For the Key transport, the SecretKey is encrypted with the recipient's public key. At the receiving
 * end, the
 * receiver can decrypt the Secret Key using his private key.s
 * </p>
 *
 * @param document
 * @param keyToBeEncrypted Symmetric Key (SecretKey)
 * @param keyUsedToEncryptSecretKey Asymmetric Key (Public Key)
 * @param keySize Length of the key
 *
 * @return
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 */
public static EncryptedKey encryptKey(Document document, SecretKey keyToBeEncrypted, PublicKey keyUsedToEncryptSecretKey,
                                      int keySize) throws ProcessingException {
    XMLCipher keyCipher;
    String pubKeyAlg = keyUsedToEncryptSecretKey.getAlgorithm();

    try {
        String keyWrapAlgo = getXMLEncryptionURLForKeyUnwrap(pubKeyAlg, keySize);
        keyCipher = XMLCipher.getInstance(keyWrapAlgo);

        keyCipher.init(XMLCipher.WRAP_MODE, keyUsedToEncryptSecretKey);
        return keyCipher.encryptKey(document, keyToBeEncrypted);
    } catch (XMLEncryptionException e) {
        throw logger.processingError(e);
    }
}
 
Example 18
Source Project: keycloak   Source File: SamlConsentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void rejectedConsentResponseTest() throws ParsingException, ConfigurationException, ProcessingException {
    ClientRepresentation client = adminClient.realm(REALM_NAME)
            .clients()
            .findByClientId(SAML_CLIENT_ID_SALES_POST)
            .get(0);

    adminClient.realm(REALM_NAME)
            .clients()
            .get(client.getId())
            .update(ClientBuilder.edit(client)
                    .consentRequired(true)
                    .attribute(SamlProtocol.SAML_IDP_INITIATED_SSO_URL_NAME, "sales-post")
                    .attribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, SAML_ASSERTION_CONSUMER_URL_SALES_POST + "saml")
                    .attribute(SamlConfigAttributes.SAML_SERVER_SIGNATURE, "true")
                    .build());

    log.debug("Log in using idp initiated login");
    SAMLDocumentHolder documentHolder = new SamlClientBuilder()
      .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, Binding.POST).build()
      .login().user(bburkeUser).build()
      .consentRequired().approveConsent(false).build()
      .getSamlResponse(Binding.POST);

    final String samlDocumentString = IOUtil.documentToString(documentHolder.getSamlDocument());
    assertThat(samlDocumentString, containsString("<dsig:Signature")); // KEYCLOAK-4262
    assertThat(samlDocumentString, not(containsString("<samlp:LogoutResponse"))); // KEYCLOAK-4261
    assertThat(samlDocumentString, containsString("<samlp:Response")); // KEYCLOAK-4261
    assertThat(samlDocumentString, containsString("<samlp:Status")); // KEYCLOAK-4181
    assertThat(samlDocumentString, containsString("<samlp:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:RequestDenied\"")); // KEYCLOAK-4181
}
 
Example 19
Source Project: keycloak   Source File: BaseWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Write an {@code AttributeType} to stream
 *
 * @param attributeType
 * @param out
 *
 * @throws ProcessingException
 */
public void write(AttributeType attributeType) throws ProcessingException {
    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.ATTRIBUTE.get(), ASSERTION_NSURI.get());

    writeAttributeTypeWithoutRootTag(attributeType);

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 20
Source Project: keycloak   Source File: SamlProtocol.java    License: Apache License 2.0 5 votes vote down vote up
protected Response buildAuthenticatedResponse(AuthenticatedClientSessionModel clientSession, String redirectUri, Document samlDocument, JaxrsSAML2BindingBuilder bindingBuilder) throws ConfigurationException, ProcessingException, IOException {
    if (isPostBinding(clientSession)) {
        return bindingBuilder.postBinding(samlDocument).response(redirectUri);
    } else {
        return bindingBuilder.redirectBinding(samlDocument).response(redirectUri);
    }
}
 
Example 21
Source Project: keycloak   Source File: SamlProtocol.java    License: Apache License 2.0 5 votes vote down vote up
protected Response buildLogoutResponse(UserSessionModel userSession, String logoutBindingUri, SAML2LogoutResponseBuilder builder, JaxrsSAML2BindingBuilder binding) throws ConfigurationException, ProcessingException, IOException {
    if (isLogoutPostBindingForInitiator(userSession)) {
        return binding.postBinding(builder.buildDocument()).response(logoutBindingUri);
    } else {
        return binding.redirectBinding(builder.buildDocument()).response(logoutBindingUri);
    }
}
 
Example 22
Source Project: keycloak   Source File: SAMLMetadataWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void writeIndexedEndpointType(IndexedEndpointType indexedEndpoint) throws ProcessingException {
    writeEndpointType(indexedEndpoint);
    if (indexedEndpoint.isIsDefault() != null)
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.ISDEFAULT.get(), "" + indexedEndpoint.isIsDefault());

    StaxUtil.writeAttribute(writer, JBossSAMLConstants.INDEX.get(), "" + indexedEndpoint.getIndex());

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 23
Source Project: keycloak   Source File: RSAKeyValueType.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert to the JDK representation of a RSA Private Key
 *
 * @return
 *
 * @throws ProcessingException
 */
public RSAPrivateKey convertToPrivateKey() throws ProcessingException {
    BigInteger bigModulus = new BigInteger(1, massage(Base64.decode(new String(modulus))));
    BigInteger bigEx = new BigInteger(1, massage(Base64.decode(new String(exponent))));

    try {
        KeyFactory rsaKeyFactory = KeyFactory.getInstance("rsa");
        RSAPrivateKeySpec kspec = new RSAPrivateKeySpec(bigModulus, bigEx);
        return (RSAPrivateKey) rsaKeyFactory.generatePrivate(kspec);
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}
 
Example 24
Source Project: keycloak   Source File: SAMLResponseWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void write(ArtifactResponseType response) throws ProcessingException {
    StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.ARTIFACT_RESPONSE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get());

    StaxUtil.writeNameSpace(writer, PROTOCOL_PREFIX, JBossSAMLURIConstants.PROTOCOL_NSURI.get());
    StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, JBossSAMLURIConstants.ASSERTION_NSURI.get());
    StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.ASSERTION_NSURI.get());

    writeBaseAttributes(response);

    NameIDType issuer = response.getIssuer();
    if (issuer != null) {
        write(issuer, new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX));
    }

    Element sig = response.getSignature();
    if (sig != null) {
        StaxUtil.writeDOMElement(writer, sig);
    }
    ExtensionsType extensions = response.getExtensions();
    if (extensions != null && extensions.getAny() != null && ! extensions.getAny().isEmpty()) {
        write(extensions);
    }

    StatusType status = response.getStatus();
    if (status != null) {
        write(status);
    }
    Object anyObj = response.getAny();
    if (anyObj instanceof AuthnRequestType) {
        AuthnRequestType authn = (AuthnRequestType) anyObj;
        SAMLRequestWriter requestWriter = new SAMLRequestWriter(writer);
        requestWriter.write(authn);
    } else if (anyObj instanceof ResponseType) {
        ResponseType rt = (ResponseType) anyObj;
        write(rt);
    }

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 25
Source Project: keycloak   Source File: SAMLMetadataWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void writeAttributeAuthorityDescriptor(AttributeAuthorityDescriptorType attributeAuthority)
        throws ProcessingException {
    StaxUtil.writeStartElement(writer, METADATA_PREFIX, JBossSAMLConstants.ATTRIBUTE_AUTHORITY_DESCRIPTOR.get(),
            JBossSAMLURIConstants.METADATA_NSURI.get());

    writeProtocolSupportEnumeration(attributeAuthority.getProtocolSupportEnumeration());

    Element signature = attributeAuthority.getSignature();
    if (signature != null) {
        StaxUtil.writeDOMElement(writer, signature);
    }
    ExtensionsType extensions = attributeAuthority.getExtensions();
    if (extensions != null) {
        StaxUtil.writeDOMElement(writer, extensions.getElement());
    }

    List<KeyDescriptorType> keyDescriptorList = attributeAuthority.getKeyDescriptor();
    for (KeyDescriptorType keyDescriptor : keyDescriptorList) {
        writeKeyDescriptor(keyDescriptor);
    }

    List<EndpointType> attributeServices = attributeAuthority.getAttributeService();
    for (EndpointType endpoint : attributeServices) {
        writeAttributeService(endpoint);
    }

    List<String> nameIDFormats = attributeAuthority.getNameIDFormat();
    for (String nameIDFormat : nameIDFormats) {
        writeNameIDFormat(nameIDFormat);
    }

    List<AttributeType> attributes = attributeAuthority.getAttribute();
    for (AttributeType attributeType : attributes) {
        write(attributeType);
    }
    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example 26
Source Project: keycloak   Source File: SAML2Request.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a Request Type from Input Stream
 *
 * @param is
 *
 * @return
 *
 * @throws ProcessingException
 * @throws ConfigurationException
 * @throws
 * @throws IllegalArgumentException inputstream is null
 */
public RequestAbstractType getRequestType(InputStream is) throws ParsingException, ConfigurationException,
        ProcessingException {
    if (is == null)
        throw logger.nullArgumentError("InputStream");

    Document samlDocument = DocumentUtil.getDocument(is);

    SAMLParser samlParser = SAMLParser.getInstance();
    JAXPValidationUtil.checkSchemaValidation(samlDocument);
    RequestAbstractType requestType = (RequestAbstractType) samlParser.parse(samlDocument);

    samlDocumentHolder = new SAMLDocumentHolder(requestType, samlDocument);
    return requestType;
}
 
Example 27
Source Project: keycloak   Source File: SAML2Request.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the DOM object
 *
 * @param rat
 *
 * @return
 *
 * @throws ProcessingException
 * @throws ParsingException
 * @throws ConfigurationException
 */
public static Document convert(RequestAbstractType rat) throws ProcessingException, ConfigurationException, ParsingException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    SAMLRequestWriter writer = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(bos));
    if (rat instanceof AuthnRequestType) {
        writer.write((AuthnRequestType) rat);
    } else if (rat instanceof LogoutRequestType) {
        writer.write((LogoutRequestType) rat);
    }

    return DocumentUtil.getDocument(new String(bos.toByteArray(), GeneralConstants.SAML_CHARSET));
}
 
Example 28
Source Project: keycloak   Source File: SAML2Request.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Marshall the AuthnRequestType to an output stream
 *
 * @param requestType
 * @param os
 *
 * @throws ProcessingException
 */
public static void marshall(RequestAbstractType requestType, OutputStream os) throws ProcessingException {
    SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(os));
    if (requestType instanceof AuthnRequestType) {
        samlRequestWriter.write((AuthnRequestType) requestType);
    } else if (requestType instanceof LogoutRequestType) {
        samlRequestWriter.write((LogoutRequestType) requestType);
    } else
        throw logger.unsupportedType(requestType.getClass().getName());
}
 
Example 29
Source Project: keycloak   Source File: SAML2Request.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Marshall the AuthnRequestType to a writer
 *
 * @param requestType
 * @param writer
 *
 * @throws ProcessingException
 */
public static void marshall(RequestAbstractType requestType, Writer writer) throws ProcessingException {
    SAMLRequestWriter samlRequestWriter = new SAMLRequestWriter(StaxUtil.getXMLStreamWriter(writer));
    if (requestType instanceof AuthnRequestType) {
        samlRequestWriter.write((AuthnRequestType) requestType);
    } else if (requestType instanceof LogoutRequestType) {
        samlRequestWriter.write((LogoutRequestType) requestType);
    } else
        throw logger.unsupportedType(requestType.getClass().getName());
}
 
Example 30
Source Project: keycloak   Source File: BaseWriter.java    License: Apache License 2.0 5 votes vote down vote up
public void writeLocalizedNameType(LocalizedNameType localizedNameType, QName startElement) throws ProcessingException {
    StaxUtil.writeStartElement(writer, startElement.getPrefix(), startElement.getLocalPart(),
            startElement.getNamespaceURI());
    StaxUtil.writeAttribute(writer, new QName(JBossSAMLURIConstants.XML.get(), "lang", "xml"), localizedNameType.getLang());
    StaxUtil.writeCharacters(writer, localizedNameType.getValue());
    StaxUtil.writeEndElement(writer);
}