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

The following examples show how to use org.keycloak.saml.common.exceptions.ProcessingException. 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
Source File: CustomSamlProtocol.java    From keycloak-extension-playground with Apache License 2.0 6 votes vote down vote up
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 File: SAML11AssertionWriter.java    From keycloak with 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 #3
Source File: BaseSAML2BindingBuilder.java    From keycloak with 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 #4
Source File: BaseSAML2BindingBuilder.java    From keycloak with 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 #5
Source File: TokenEndpoint.java    From keycloak with 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 #6
Source File: BaseWriter.java    From keycloak with 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 File: BrokerTest.java    From keycloak with 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 #8
Source File: BrokerTest.java    From keycloak with 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 #9
Source File: SamlUtil.java    From keycloak with 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 #10
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: SamlClient.java    From keycloak with 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 #12
Source File: SamlClient.java    From keycloak with 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 #13
Source File: SAMLResponseWriter.java    From keycloak with 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 #14
Source File: SAML2Response.java    From keycloak with 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 #15
Source File: SAMLResponseWriter.java    From keycloak with 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 #16
Source File: CreateAuthnRequestStepBuilder.java    From keycloak with 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 File: XMLEncryptionUtil.java    From keycloak with 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 File: SAML2Request.java    From keycloak with 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 #19
Source File: AssertionUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean isAssertionEncrypted(ResponseType responseType) throws ProcessingException {
    List<ResponseType.RTChoiceType> assertions = responseType.getAssertions();

    if (assertions.isEmpty()) {
        throw new ProcessingException("No assertion from response.");
    }

    ResponseType.RTChoiceType rtChoiceType = assertions.get(0);
    return rtChoiceType.getEncryptedAssertion() != null;
}
 
Example #20
Source File: SAML2Request.java    From keycloak with 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 #21
Source File: SamlConsentTest.java    From keycloak with 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 #22
Source File: StaxUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Write an attribute
 *
 * @param writer
 * @param attributeName QName of the attribute
 * @param attributeValue
 *
 * @throws ProcessingException
 */
public static void writeAttribute(XMLStreamWriter writer, QName attributeName, String attributeValue)
        throws ProcessingException {
    try {
        writer.writeAttribute(attributeName.getPrefix(), attributeName.getNamespaceURI(), attributeName.getLocalPart(),
                attributeValue);
    } catch (XMLStreamException e) {
        throw logger.processingError(e);
    }
}
 
Example #23
Source File: SamlProtocol.java    From keycloak with 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 #24
Source File: SAMLMetadataWriter.java    From keycloak with 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 #25
Source File: SAMLMetadataWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void writeLocalizedType(LocalizedNameType localName) throws ProcessingException {
    String lang = localName.getLang();
    String val = localName.getValue();
    StaxUtil.writeAttribute(writer, new QName(JBossSAMLURIConstants.XML.get(), JBossSAMLConstants.LANG.get(), "xml"), lang);

    StaxUtil.writeCharacters(writer, val);

    StaxUtil.writeEndElement(writer);
}
 
Example #26
Source File: BaseWriter.java    From keycloak with 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);
}
 
Example #27
Source File: RSAKeyValueType.java    From keycloak with 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 #28
Source File: SAMLMetadataWriter.java    From keycloak with 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 #29
Source File: SAMLAssertionWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Write an {@code AuthnStatementType} to stream
 *
 * @param authnStatement
 *
 * @throws ProcessingException
 */
public void write(AuthnStatementType authnStatement, boolean includeNamespace) throws ProcessingException {
    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.AUTHN_STATEMENT.get(), ASSERTION_NSURI.get());
    if (includeNamespace) {
        StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, ASSERTION_NSURI.get());
        StaxUtil.writeDefaultNameSpace(writer, ASSERTION_NSURI.get());
    }

    XMLGregorianCalendar authnInstant = authnStatement.getAuthnInstant();
    if (authnInstant != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.AUTHN_INSTANT.get(), authnInstant.toString());
    }

    String sessionIndex = authnStatement.getSessionIndex();

    if (sessionIndex != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.SESSION_INDEX.get(), sessionIndex);
    }

    XMLGregorianCalendar sessionNotOnOrAfter = authnStatement.getSessionNotOnOrAfter();
    if (sessionNotOnOrAfter != null) {
        StaxUtil.writeAttribute(writer, SAMLAssertionQNames.ATTR_SESSION_NOT_ON_OR_AFTER.getQName(), sessionNotOnOrAfter.toString());
    }

    AuthnContextType authnContext = authnStatement.getAuthnContext();
    if (authnContext != null)
        write(authnContext);

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example #30
Source File: SAML2Signature.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Sign a SAML Document
 *
 * @param samlDocument
 * @param keypair
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 */
public void signSAMLDocument(Document samlDocument, String keyName, KeyPair keypair, String canonicalizationMethodType) throws ProcessingException {
    // Get the ID from the root
    String id = samlDocument.getDocumentElement().getAttribute(JBossSAMLConstants.ID.get());
    try {
        sign(samlDocument, id, keyName, keypair, canonicalizationMethodType);
    } catch (ParserConfigurationException | GeneralSecurityException | MarshalException | XMLSignatureException e) {
        throw new ProcessingException(logger.signatureError(e));
    }
}