use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.
the class CreateAuthnRequestStepBuilder method createLoginRequestDocument.
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());
if (protocolBinding != null) {
loginReq.setProtocolBinding(protocolBinding);
}
return SAML2Request.convert(loginReq);
} catch (ConfigurationException | ParsingException | ProcessingException ex) {
throw new RuntimeException(ex);
}
}
use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.
the class KcSamlCustomEntityIdBrokerTest method testCustomEntityNotSet.
@Test
public void testCustomEntityNotSet() throws Exception {
// No comparison type, no classrefs, no declrefs -> No RequestedAuthnContext
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource).update()) {
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
Binding.POST).targetAttributeSamlRequest().transformDocument((document) -> {
try {
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the Issuer element
Element issuerElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), ASSERTION_NSURI.get(), "Issuer");
Assert.assertEquals("Unexpected Issuer element value", getAuthServerRoot() + "realms/consumer", issuerElement.getTextContent());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}).build().execute();
}
}
use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.
the class KcSamlEncryptedIdTest method testEncryptedIdIsReadable.
@Test
public void testEncryptedIdIsReadable() throws ConfigurationException, ParsingException, ProcessingException {
createRolesForRealm(bc.consumerRealmName());
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
final AtomicReference<String> username = new AtomicReference<>();
assertThat(adminClient.realm(bc.consumerRealmName()).users().search(username.get()), hasSize(0));
SAMLDocumentHolder samlResponse = new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, SamlClient.Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
SamlClient.Binding.POST).targetAttributeSamlRequest().build().login().user(bc.getUserLogin(), bc.getUserPassword()).build().processSamlResponse(// Response from producer IdP
SamlClient.Binding.POST).transformDocument(document -> {
// Replace Subject -> NameID with EncryptedId
Node assertionElement = document.getDocumentElement().getElementsByTagNameNS(ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()).item(0);
if (assertionElement == null) {
throw new IllegalStateException("Unable to find assertion in saml response document");
}
String samlNSPrefix = assertionElement.getPrefix();
try {
QName encryptedIdElementQName = new QName(ASSERTION_NSURI.get(), JBossSAMLConstants.ENCRYPTED_ID.get(), samlNSPrefix);
QName nameIdQName = new QName(ASSERTION_NSURI.get(), JBossSAMLConstants.NAMEID.get(), samlNSPrefix);
// Add xmlns:saml attribute to NameId element,
// this is necessary as it is decrypted as a separate doc and saml namespace is not know
// unless added to NameId element
Element nameIdElement = DocumentUtil.getElement(document, nameIdQName);
if (nameIdElement == null) {
throw new RuntimeException("Assertion doesn't contain NameId " + DocumentUtil.asString(document));
}
nameIdElement.setAttribute("xmlns:" + samlNSPrefix, ASSERTION_NSURI.get());
username.set(nameIdElement.getTextContent());
byte[] secret = RandomSecret.createRandomSecret(128 / 8);
SecretKey secretKey = new SecretKeySpec(secret, "AES");
// encrypt the Assertion element and replace it with a EncryptedAssertion element.
XMLEncryptionUtil.encryptElement(nameIdQName, document, PemUtils.decodePublicKey(ApiUtil.findActiveSigningKey(adminClient.realm(bc.consumerRealmName())).getPublicKey()), secretKey, 128, encryptedIdElementQName, true);
} catch (Exception e) {
throw new ProcessingException("failed to encrypt", e);
}
assertThat(DocumentUtil.asString(document), not(containsString(username.get())));
return document;
}).build().updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).build().followOneRedirect().getSamlResponse(// Response from consumer IdP
SamlClient.Binding.POST);
assertThat(samlResponse, Matchers.notNullValue());
assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
assertThat(adminClient.realm(bc.consumerRealmName()).users().search(username.get()), hasSize(1));
}
use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.
the class KcSamlLogoutTest method testProviderInitiatedLogoutCorrectlyLogsOutConsumerClients.
@Test
public void testProviderInitiatedLogoutCorrectlyLogsOutConsumerClients() throws Exception {
try (SamlMessageReceiver logoutReceiver = new SamlMessageReceiver(8082);
ClientAttributeUpdater cauConsumer = ClientAttributeUpdater.forClient(adminClient, bc.consumerRealmName(), AbstractSamlTest.SAML_CLIENT_ID_SALES_POST).setFrontchannelLogout(false).setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, logoutReceiver.getUrl()).update();
ClientAttributeUpdater cauProvider = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm()).setFrontchannelLogout(true).update()) {
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
final AtomicReference<NameIDType> nameIdRef = new AtomicReference<>();
final AtomicReference<String> sessionIndexRef = new AtomicReference<>();
new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, SamlClient.Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
SamlClient.Binding.POST).targetAttributeSamlRequest().build().login().user(bc.getUserLogin(), bc.getUserPassword()).build().processSamlResponse(// Response from producer IdP
SamlClient.Binding.POST).build().updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build().followOneRedirect().processSamlResponse(SamlClient.Binding.POST).transformObject(saml2Object -> {
assertThat(saml2Object, Matchers.notNullValue());
assertThat(saml2Object, isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
return null;
}).build().authnRequest(getProviderSamlEndpoint(bc.providerRealmName()), PROVIDER_SAML_CLIENT_ID, PROVIDER_SAML_CLIENT_ID + "saml", POST).build().followOneRedirect().processSamlResponse(POST).transformObject(saml2Object -> {
assertThat(saml2Object, isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
ResponseType loginResp1 = (ResponseType) saml2Object;
final AssertionType firstAssertion = loginResp1.getAssertions().get(0).getAssertion();
assertThat(firstAssertion, Matchers.notNullValue());
assertThat(firstAssertion.getSubject().getSubType().getBaseID(), instanceOf(NameIDType.class));
NameIDType nameId = (NameIDType) firstAssertion.getSubject().getSubType().getBaseID();
AuthnStatementType firstAssertionStatement = (AuthnStatementType) firstAssertion.getStatements().iterator().next();
nameIdRef.set(nameId);
sessionIndexRef.set(firstAssertionStatement.getSessionIndex());
return null;
}).build().logoutRequest(getProviderSamlEndpoint(bc.providerRealmName()), PROVIDER_SAML_CLIENT_ID, POST).nameId(nameIdRef::get).sessionIndex(sessionIndexRef::get).build().processSamlResponse(POST).transformObject(saml2Object -> {
assertThat(saml2Object, isSamlLogoutRequest(getConsumerRoot() + "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_SAML_ALIAS + "/endpoint"));
return saml2Object;
}).build().executeAndTransform(response -> {
SAMLDocumentHolder saml2ObjectHolder = POST.extractResponse(response);
assertThat(saml2ObjectHolder.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
return null;
});
// Check whether logoutReceiver contains correct LogoutRequest
assertThat(logoutReceiver.isMessageReceived(), is(true));
SAMLDocumentHolder message = logoutReceiver.getSamlDocumentHolder();
assertThat(message.getSamlObject(), isSamlLogoutRequest(logoutReceiver.getUrl()));
}
}
use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.
the class KcSamlRequestedAuthnContextBrokerTest method testComparisonTypeSetClassRefsSetNoDeclRefs.
@Test
public void testComparisonTypeSetClassRefsSetNoDeclRefs() throws Exception {
// Comparison type set, classref present, no declrefs -> RequestedAuthnContext with AuthnContextClassRef
try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource).setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_COMPARISON_TYPE, AuthnContextComparisonType.EXACT.value()).setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_CLASS_REFS, "[\"" + AC_PASSWORD_PROTECTED_TRANSPORT.get() + "\"]").update()) {
// Build the login request document
AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
Document doc = SAML2Request.convert(loginRep);
new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
Binding.POST).targetAttributeSamlRequest().transformDocument((document) -> {
try {
log.infof("Document: %s", DocumentUtil.asString(document));
// Find the RequestedAuthnContext element
Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement, Matchers.notNullValue());
// Verify the ComparisonType attribute
Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement.getAttribute("Comparison"), Matchers.is(AuthnContextComparisonType.EXACT.value()));
// Find the RequestedAuthnContext/ClassRef element
Element requestedAuthnContextClassRefElement = DocumentUtil.getDirectChildElement(requestedAuthnContextElement, ASSERTION_NSURI.get(), "AuthnContextClassRef");
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element not found in request document", requestedAuthnContextClassRefElement, Matchers.notNullValue());
// Make sure the RequestedAuthnContext/ClassRef element has the requested value
Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element does not have the expected value", requestedAuthnContextClassRefElement.getTextContent(), Matchers.is(AC_PASSWORD_PROTECTED_TRANSPORT.get()));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}).build().execute();
}
}
Aggregations