KEYCLOAK-8522: Migrate IdpHint tests. Remove unneeded tests.

This commit is contained in:
Stan Silvert 2019-02-11 07:06:24 -05:00 committed by Pedro Igor
parent fe5966d224
commit 05005a1791
8 changed files with 253 additions and 754 deletions

View file

@ -3,7 +3,6 @@ package org.keycloak.testsuite.broker;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.admin.client.resource.IdentityProviderResource;
@ -42,77 +41,21 @@ import org.openqa.selenium.WebElement;
import javax.ws.rs.core.Response;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static org.keycloak.testsuite.broker.BrokerTestTools.*;
public abstract class AbstractBrokerTest extends AbstractBaseBrokerTest {
public abstract class AbstractBrokerTest extends AbstractInitializedBaseBrokerTest {
public static final String ROLE_USER = "user";
public static final String ROLE_MANAGER = "manager";
public static final String ROLE_FRIENDLY_MANAGER = "friendly-manager";
protected IdentityProviderResource identityProviderResource;
@Drone
@SecondBrowser
protected WebDriver driver2;
@Before
public void beforeBrokerTest() {
log.debug("creating user for realm " + bc.providerRealmName());
UserRepresentation user = new UserRepresentation();
user.setUsername(bc.getUserLogin());
user.setEmail(bc.getUserEmail());
user.setEmailVerified(true);
user.setEnabled(true);
RealmResource realmResource = adminClient.realm(bc.providerRealmName());
userId = createUserWithAdminClient(realmResource, user);
resetUserPassword(realmResource.users().get(userId), bc.getUserPassword(), false);
if (testContext.isInitialized()) {
if (identityProviderResource == null) {
identityProviderResource = (IdentityProviderResource) testContext.getCustomValue("identityProviderResource");
}
return;
}
log.debug("adding identity provider to realm " + bc.consumerRealmName());
RealmResource realm = adminClient.realm(bc.consumerRealmName());
realm.identityProviders().create(bc.setUpIdentityProvider(suiteContext)).close();
identityProviderResource = realm.identityProviders().get(bc.getIDPAlias());
testContext.setCustomValue("identityProviderResource", identityProviderResource);
// addClients
List<ClientRepresentation> clients = bc.createProviderClients(suiteContext);
if (clients != null) {
RealmResource providerRealm = adminClient.realm(bc.providerRealmName());
for (ClientRepresentation client : clients) {
log.debug("adding client " + client.getClientId()+ " to realm " + bc.providerRealmName());
providerRealm.clients().create(client).close();
}
}
clients = bc.createConsumerClients(suiteContext);
if (clients != null) {
RealmResource consumerRealm = adminClient.realm(bc.consumerRealmName());
for (ClientRepresentation client : clients) {
log.debug("adding client " + client.getClientId() + " to realm " + bc.consumerRealmName());
consumerRealm.clients().create(client).close();
}
}
testContext.setInitialized(true);
}
@Test
public void testLogInAsUserInIDP() {
loginUser();

View file

@ -0,0 +1,88 @@
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import org.junit.Before;
import org.keycloak.admin.client.resource.IdentityProviderResource;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import java.util.List;
import static org.keycloak.testsuite.admin.ApiUtil.createUserWithAdminClient;
import static org.keycloak.testsuite.admin.ApiUtil.resetUserPassword;
/**
* @author Stan Silvert ssilvert@redhat.com (C) 2019 Red Hat Inc.
*/
public abstract class AbstractInitializedBaseBrokerTest extends AbstractBaseBrokerTest {
protected IdentityProviderResource identityProviderResource;
@Before
public void beforeBrokerTest() {
log.debug("creating user for realm " + bc.providerRealmName());
UserRepresentation user = new UserRepresentation();
user.setUsername(bc.getUserLogin());
user.setEmail(bc.getUserEmail());
user.setEmailVerified(true);
user.setEnabled(true);
RealmResource realmResource = adminClient.realm(bc.providerRealmName());
userId = createUserWithAdminClient(realmResource, user);
resetUserPassword(realmResource.users().get(userId), bc.getUserPassword(), false);
if (testContext.isInitialized()) {
if (identityProviderResource == null) {
identityProviderResource = (IdentityProviderResource) testContext.getCustomValue("identityProviderResource");
}
return;
}
log.debug("adding identity provider to realm " + bc.consumerRealmName());
RealmResource realm = adminClient.realm(bc.consumerRealmName());
realm.identityProviders().create(bc.setUpIdentityProvider(suiteContext)).close();
identityProviderResource = realm.identityProviders().get(bc.getIDPAlias());
testContext.setCustomValue("identityProviderResource", identityProviderResource);
// addClients
List<ClientRepresentation> clients = bc.createProviderClients(suiteContext);
if (clients != null) {
RealmResource providerRealm = adminClient.realm(bc.providerRealmName());
for (ClientRepresentation client : clients) {
log.debug("adding client " + client.getClientId()+ " to realm " + bc.providerRealmName());
providerRealm.clients().create(client).close();
}
}
clients = bc.createConsumerClients(suiteContext);
if (clients != null) {
RealmResource consumerRealm = adminClient.realm(bc.consumerRealmName());
for (ClientRepresentation client : clients) {
log.debug("adding client " + client.getClientId() + " to realm " + bc.consumerRealmName());
consumerRealm.clients().create(client).close();
}
}
testContext.setInitialized(true);
}
}

View file

@ -0,0 +1,73 @@
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import java.util.Map;
import org.junit.Test;
import org.keycloak.representations.idm.IdentityProviderRepresentation;
import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage;
import org.keycloak.testsuite.Assert;
import org.keycloak.testsuite.arquillian.SuiteContext;
import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_ALIAS;
import static org.keycloak.testsuite.broker.BrokerTestConstants.IDP_OIDC_PROVIDER_ID;
import static org.keycloak.testsuite.broker.BrokerTestTools.createIdentityProvider;
/**
* Migrated from old testsuite. Previous version by Pedro Igor.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2019 Red Hat Inc.
* @author pedroigor
*/
public class KcOidcBrokerHiddenIdpHintTest extends AbstractInitializedBaseBrokerTest {
@Override
protected BrokerConfiguration getBrokerConfiguration() {
return new KcOidcHiddenBrokerConfiguration();
}
private class KcOidcHiddenBrokerConfiguration extends KcOidcBrokerConfiguration {
@Override
public IdentityProviderRepresentation setUpIdentityProvider(SuiteContext suiteContext) {
IdentityProviderRepresentation idp = createIdentityProvider(IDP_OIDC_ALIAS, IDP_OIDC_PROVIDER_ID);
Map<String, String> config = idp.getConfig();
applyDefaultConfiguration(suiteContext, config);
config.put("hideOnLoginPage", "true");
return idp;
}
}
@Test
public void testSuccessfulRedirectToProviderHiddenOnLoginPage() {
driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
waitForPage(driver, "log in to", true);
String url = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias();
driver.navigate().to(url);
waitForPage(driver, "log in to", true);
Assert.assertTrue("Driver should be on the provider realm page right now",
driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
log.debug("Logging in");
accountLoginPage.login(bc.getUserLogin(), bc.getUserPassword());
// authenticated and redirected to app
Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"));
}
}

View file

@ -0,0 +1,91 @@
/*
* Copyright 2019 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import org.junit.Test;
import static org.keycloak.testsuite.broker.BrokerTestTools.waitForPage;
import org.keycloak.testsuite.Assert;
/**
* Migrated from old testsuite. Previous version by Pedro Igor.
*
* @author Stan Silvert ssilvert@redhat.com (C) 2019 Red Hat Inc.
* @author pedroigor
*/
public class KcOidcBrokerIdpHintTest extends AbstractInitializedBaseBrokerTest {
@Override
protected BrokerConfiguration getBrokerConfiguration() {
return new KcOidcBrokerConfiguration();
}
@Test
public void testSuccessfulRedirect() {
driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
waitForPage(driver, "log in to", true);
String url = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias();
driver.navigate().to(url);
waitForPage(driver, "log in to", true);
Assert.assertTrue("Driver should be on the provider realm page right now",
driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
log.debug("Logging in");
accountLoginPage.login(bc.getUserLogin(), bc.getUserPassword());
// authenticated and redirected to app
Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"));
}
// KEYCLOAK-5260
@Test
public void testSuccessfulRedirectToProviderAfterLoginPageShown() {
driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
waitForPage(driver, "log in to", true);
String urlWithHint = driver.getCurrentUrl() + "&kc_idp_hint=" + bc.getIDPAlias();
driver.navigate().to(urlWithHint);
waitForPage(driver, "log in to", true);
Assert.assertTrue("Driver should be on the provider realm page right now",
driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
// do the same thing a second time
driver.navigate().to(urlWithHint);
waitForPage(driver, "log in to", true);
Assert.assertTrue("Driver should be on the provider realm page right now",
driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
// redirect shouldn't happen
driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
waitForPage(driver, "log in to", true);
Assert.assertTrue("Driver should be on the consumer realm page",
driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"));
}
@Test
public void testInvalidIdentityProviderHint() {
driver.navigate().to(getAccountUrl(bc.consumerRealmName()));
waitForPage(driver, "log in to", true);
String url = driver.getCurrentUrl() + "&kc_idp_hint=bogus-idp";
driver.navigate().to(url);
waitForPage(driver, "log in to", true);
// Still on consumer login page
Assert.assertTrue(driver.getCurrentUrl().contains("/auth/realms/" + bc.consumerRealmName() + "/"));
}
}

View file

@ -272,37 +272,6 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractIdentityProvi
assertFederatedUser("testing-user", "testing-user@redhat.com", "pedroigor");
}
/**
* Tests that duplication is detected and user wants to link federatedIdentity with existing account. He will confirm link by email
*/
@Test
public void testLinkAccountByEmailVerification() throws Exception {
setUpdateProfileFirstLogin(IdentityProviderRepresentation.UPFLM_OFF);
loginIDP("pedroigor");
this.idpConfirmLinkPage.assertCurrent();
Assert.assertEquals("User with email psilva@redhat.com already exists. How do you want to continue?", this.idpConfirmLinkPage.getMessage());
this.idpConfirmLinkPage.clickLinkAccount();
// Confirm linking account by email
this.idpLinkEmailPage.assertCurrent();
Assert.assertEquals("An email with instructions to link " + ObjectUtil.capitalize(getProviderId()) + " account pedroigor with your " + APP_REALM_ID + " account has been sent to you.", this.idpLinkEmailPage.getMessage());
Assert.assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String linkFromMail = getVerificationEmailLink(message);
driver.navigate().to(linkFromMail.trim());
// authenticated and redirected to app. User is linked with identity provider
assertFederatedUser("pedroigor", "psilva@redhat.com", "pedroigor");
// Assert user's email is verified now
UserModel user = getFederatedUser();
Assert.assertTrue(user.isEmailVerified());
}
/**
* Tests that duplication is detected and user wants to link federatedIdentity with existing account. He will confirm link by email
*/
@ -355,61 +324,6 @@ public abstract class AbstractFirstBrokerLoginTest extends AbstractIdentityProvi
Assert.assertThat(infoPage.getInfo(), startsWith("You successfully verified your email. Please go back to your original browser and continue there with the login."));
}
/**
* Tests that duplication is detected and user wants to link federatedIdentity with existing account. He will confirm link by email
*/
@Test
public void testLinkAccountByEmailVerificationDifferentBrowser() throws Exception, Throwable {
setUpdateProfileFirstLogin(IdentityProviderRepresentation.UPFLM_OFF);
loginIDP("pedroigor");
this.idpConfirmLinkPage.assertCurrent();
Assert.assertEquals("User with email psilva@redhat.com already exists. How do you want to continue?", this.idpConfirmLinkPage.getMessage());
this.idpConfirmLinkPage.clickLinkAccount();
// Confirm linking account by email
this.idpLinkEmailPage.assertCurrent();
Assert.assertThat(
this.idpLinkEmailPage.getMessage(),
is("An email with instructions to link " + ObjectUtil.capitalize(getProviderId()) + " account pedroigor with your " + APP_REALM_ID + " account has been sent to you.")
);
Assert.assertEquals(1, greenMail.getReceivedMessages().length);
MimeMessage message = greenMail.getReceivedMessages()[0];
String linkFromMail = getVerificationEmailLink(message);
WebRule webRule2 = new WebRule(this);
try {
webRule2.initProperties();
WebDriver driver2 = webRule2.getDriver();
InfoPage infoPage2 = webRule2.getPage(InfoPage.class);
ProceedPage proceedPage2 = webRule2.getPage(ProceedPage.class);
driver2.navigate().to(linkFromMail.trim());
// authenticated, but not redirected to app. Just seeing info page.
proceedPage2.assertCurrent();
Assert.assertThat(proceedPage2.getInfo(), Matchers.containsString("Confirm linking the account"));
proceedPage2.clickProceedLink();
infoPage2.assertCurrent();
Assert.assertThat(infoPage2.getInfo(), startsWith("You successfully verified your email. Please go back to your original browser and continue there with the login."));
} finally {
// Revert everything
webRule2.after();
}
this.idpLinkEmailPage.clickContinueFlowLink();
// authenticated and redirected to app. User is linked with identity provider
assertFederatedUser("pedroigor", "psilva@redhat.com", "pedroigor");
// Assert user's email is verified now
UserModel user = getFederatedUser();
Assert.assertTrue(user.isEmailVerified());
}
@Test
public void testLinkAccountByEmailVerificationResendEmail() throws Exception, Throwable {
setUpdateProfileFirstLogin(IdentityProviderRepresentation.UPFLM_OFF);

View file

@ -1,139 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.KeycloakServer;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.pages.OAuthGrantPage;
import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.openqa.selenium.WebDriver;
import static org.junit.Assert.assertTrue;
/**
* @author pedroigor
*/
public class IdentityProviderHintTest {
@ClassRule
public static BrokerKeyCloakRule keycloakRule = new BrokerKeyCloakRule();
@ClassRule
public static AbstractKeycloakRule samlServerRule = new AbstractKeycloakRule() {
@Override
protected void configureServer(KeycloakServer server) {
server.getConfig().setPort(8082);
}
@Override
protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) {
server.importRealm(getClass().getResourceAsStream("/broker-test/test-broker-realm-with-kc-oidc.json"));
}
@Override
protected String[] getTestRealms() {
return new String[] { "realm-with-oidc-identity-provider" };
}
};
@Rule
public WebRule webRule = new WebRule(this);
@WebResource
private WebDriver driver;
@WebResource
private LoginPage loginPage;
@WebResource
private OAuthGrantPage grantPage;
@Test
public void testSuccessfulRedirect() {
this.driver.navigate().to("http://localhost:8081/test-app?kc_idp_hint=kc-oidc-idp");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/"));
// log in to identity provider
this.loginPage.login("test-user", "password");
// authenticated and redirected to app
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app"));
assertTrue(this.driver.getPageSource().contains("idToken"));
}
@Test
public void testSuccessfulRedirectToProviderHiddenOnLoginPage() {
this.driver.navigate().to("http://localhost:8081/test-app?kc_idp_hint=kc-oidc-idp-hidden");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/"));
}
// KEYCLOAK-5260
@Test
public void testSuccessfulRedirectToProviderAfterLoginPageShown() {
this.driver.navigate().to("http://localhost:8081/test-app");
String loginPageUrl = driver.getCurrentUrl();
assertTrue(loginPageUrl.startsWith("http://localhost:8081/auth/"));
// Manually add "kc_idp_hint" to URL . Should redirect to provider
loginPageUrl = loginPageUrl + "&kc_idp_hint=kc-oidc-idp-hidden";
this.driver.navigate().to(loginPageUrl);
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/"));
// Redirect from the app with the "kc_idp_hint". Should redirect to provider
this.driver.navigate().to("http://localhost:8081/test-app?kc_idp_hint=kc-oidc-idp-hidden");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/"));
// Now redirect should't happen
this.driver.navigate().to("http://localhost:8081/test-app");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/"));
}
@Test
public void testInvalidIdentityProviderHint() {
this.driver.navigate().to("http://localhost:8081/test-app?kc_idp_hint=invalid-idp-id");
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/auth"));
System.out.println(driver.getPageSource());
assertTrue(driver.getTitle().equals("Log in to realm-with-broker"));
}
private AuthenticationExecutionInfoRepresentation findExecution(RealmResource realm) {
for (AuthenticationExecutionInfoRepresentation e : realm.flows().getExecutions("browser")) {
if (e.getProviderId().equals("identity-provider-redirector")) {
return e;
}
}
return null;
}
}

View file

@ -1,106 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import org.junit.Test;
import org.keycloak.broker.provider.IdentityProvider;
import org.keycloak.broker.provider.IdentityProviderFactory;
import org.keycloak.broker.social.SocialIdentityProvider;
import org.keycloak.broker.social.SocialIdentityProviderFactory;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.testsuite.broker.provider.CustomIdentityProvider;
import org.keycloak.testsuite.broker.provider.CustomIdentityProviderFactory;
import org.keycloak.testsuite.broker.provider.social.CustomSocialProvider;
import org.keycloak.testsuite.broker.provider.social.CustomSocialProviderFactory;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author pedroigor
*/
public class IdentityProviderRegistrationTest extends AbstractIdentityProviderModelTest {
@Test
public void testIdentityProviderRegistration() {
Set<String> installedProviders = getInstalledProviders();
for (String providerId : getExpectedProviders()) {
if (!installedProviders.contains(providerId)) {
fail("Provider [" + providerId + "] not installed ");
}
}
}
@Test
public void testCustomSocialProviderRegistration() {
String providerId = CustomSocialProviderFactory.PROVIDER_ID;
assertTrue(getInstalledProviders().contains(providerId));
SocialIdentityProviderFactory<CustomSocialProvider> providerFactory = (SocialIdentityProviderFactory) this.session.getKeycloakSessionFactory().getProviderFactory(SocialIdentityProvider.class, providerId);
assertNotNull(providerFactory);
IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setAlias("custom-provider");
CustomSocialProvider customSocialProvider = providerFactory.create(this.session, identityProviderModel);
assertNotNull(customSocialProvider);
IdentityProviderModel config = customSocialProvider.getConfig();
assertNotNull(config);
assertEquals("custom-provider", config.getAlias());
}
@Test
public void testCustomIdentityProviderRegistration() {
String providerId = CustomIdentityProviderFactory.PROVIDER_ID;
assertTrue(getInstalledProviders().contains(providerId));
IdentityProviderFactory<CustomIdentityProvider> providerFactory = (IdentityProviderFactory) this.session.getKeycloakSessionFactory().getProviderFactory(IdentityProvider.class, providerId);
assertNotNull(providerFactory);
IdentityProviderModel identityProviderModel = new IdentityProviderModel();
identityProviderModel.setAlias("custom-provider");
CustomIdentityProvider provider = providerFactory.create(this.session, identityProviderModel);
assertNotNull(provider);
IdentityProviderModel config = provider.getConfig();
assertNotNull(config);
assertEquals("custom-provider", config.getAlias());
}
private Set<String> getInstalledProviders() {
Set<String> installedProviders = this.session.listProviderIds(IdentityProvider.class);
installedProviders.addAll(this.session.listProviderIds(SocialIdentityProvider.class));
return installedProviders;
}
}

View file

@ -1,365 +0,0 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.testsuite.broker;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.broker.oidc.OAuth2IdentityProviderConfig;
import org.keycloak.broker.oidc.OIDCIdentityProvider;
import org.keycloak.broker.oidc.OIDCIdentityProviderConfig;
import org.keycloak.broker.oidc.OIDCIdentityProviderFactory;
import org.keycloak.broker.saml.SAMLIdentityProvider;
import org.keycloak.broker.saml.SAMLIdentityProviderConfig;
import org.keycloak.broker.saml.SAMLIdentityProviderFactory;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.social.facebook.FacebookIdentityProvider;
import org.keycloak.social.facebook.FacebookIdentityProviderFactory;
import org.keycloak.social.github.GitHubIdentityProvider;
import org.keycloak.social.github.GitHubIdentityProviderFactory;
import org.keycloak.social.paypal.PayPalIdentityProvider;
import org.keycloak.social.paypal.PayPalIdentityProviderFactory;
import org.keycloak.social.paypal.PayPalIdentityProviderConfig;
import org.keycloak.social.google.GoogleIdentityProvider;
import org.keycloak.social.google.GoogleIdentityProviderFactory;
import org.keycloak.social.linkedin.LinkedInIdentityProvider;
import org.keycloak.social.linkedin.LinkedInIdentityProviderFactory;
import org.keycloak.social.openshift.OpenshiftV3IdentityProviderConfig;
import org.keycloak.social.openshift.OpenshiftV3IdentityProvider;
import org.keycloak.social.openshift.OpenshiftV3IdentityProviderFactory;
import org.keycloak.social.stackoverflow.StackOverflowIdentityProviderConfig;
import org.keycloak.social.stackoverflow.StackoverflowIdentityProvider;
import org.keycloak.social.stackoverflow.StackoverflowIdentityProviderFactory;
import org.keycloak.social.twitter.TwitterIdentityProvider;
import org.keycloak.social.twitter.TwitterIdentityProviderFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author pedroigor
*/
public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTest {
@Test
public void testInstallation() throws Exception {
RealmModel realm = installTestRealm();
assertIdentityProviderConfig(realm, realm.getIdentityProviders());
assertTrue(realm.isIdentityFederationEnabled());
this.realmManager.removeRealm(realm);
}
@Test
public void testUpdateIdentityProvider() throws Exception {
RealmModel realm = installTestRealm();
List<IdentityProviderModel> identityProviders = realm.getIdentityProviders();
assertFalse(identityProviders.isEmpty());
IdentityProviderModel identityProviderModel = identityProviders.get(0);
String identityProviderId = identityProviderModel.getAlias();
identityProviderModel.getConfig().put("config-added", "value-added");
identityProviderModel.setEnabled(false);
identityProviderModel.setTrustEmail(true);
identityProviderModel.setStoreToken(true);
identityProviderModel.setAuthenticateByDefault(true);
identityProviderModel.setFirstBrokerLoginFlowId(realm.getBrowserFlow().getId());
identityProviderModel.setPostBrokerLoginFlowId(realm.getDirectGrantFlow().getId());
realm.updateIdentityProvider(identityProviderModel);
commit();
realm = this.realmManager.getRealm(realm.getId());
identityProviderModel = realm.getIdentityProviderByAlias(identityProviderId);
assertEquals("value-added", identityProviderModel.getConfig().get("config-added"));
assertFalse(identityProviderModel.isEnabled());
assertTrue(identityProviderModel.isTrustEmail());
assertTrue(identityProviderModel.isStoreToken());
assertTrue(identityProviderModel.isAuthenticateByDefault());
assertEquals(identityProviderModel.getFirstBrokerLoginFlowId(), realm.getBrowserFlow().getId());
assertEquals(identityProviderModel.getPostBrokerLoginFlowId(), realm.getDirectGrantFlow().getId());
identityProviderModel.getConfig().remove("config-added");
identityProviderModel.setEnabled(true);
identityProviderModel.setTrustEmail(false);
identityProviderModel.setAuthenticateByDefault(false);
realm.updateIdentityProvider(identityProviderModel);
commit();
realm = this.realmManager.getRealm(realm.getId());
identityProviderModel = realm.getIdentityProviderByAlias(identityProviderId);
assertFalse(identityProviderModel.getConfig().containsKey("config-added"));
assertTrue(identityProviderModel.isEnabled());
assertFalse(identityProviderModel.isTrustEmail());
assertFalse(identityProviderModel.isAuthenticateByDefault());
this.realmManager.removeRealm(realm);
}
private void assertIdentityProviderConfig(RealmModel realm, List<IdentityProviderModel> identityProviders) {
assertFalse(identityProviders.isEmpty());
Set<String> checkedProviders = new HashSet<String>(getExpectedProviders());
for (IdentityProviderModel identityProvider : identityProviders) {
if (identityProvider.getAlias().startsWith("model-")) {
String providerId = identityProvider.getProviderId();
if (SAMLIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertSamlIdentityProviderConfig(identityProvider);
} else if (GoogleIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertGoogleIdentityProviderConfig(identityProvider);
} else if (OIDCIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertOidcIdentityProviderConfig(identityProvider);
} else if (FacebookIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertFacebookIdentityProviderConfig(realm, identityProvider);
} else if (GitHubIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertGitHubIdentityProviderConfig(realm, identityProvider);
} else if (PayPalIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertPayPalIdentityProviderConfig(realm, identityProvider);
} else if (TwitterIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertTwitterIdentityProviderConfig(identityProvider);
} else if (LinkedInIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertLinkedInIdentityProviderConfig(identityProvider);
} else if (StackoverflowIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertStackoverflowIdentityProviderConfig(identityProvider);
} else if (OpenshiftV3IdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertOpenshiftIdentityProviderConfig(identityProvider);
} else {
continue;
}
checkedProviders.remove(providerId);
}
}
assertTrue(checkedProviders.isEmpty());
}
private void assertGoogleIdentityProviderConfig(IdentityProviderModel identityProvider) {
GoogleIdentityProvider googleIdentityProvider = new GoogleIdentityProviderFactory().create(session, identityProvider);
OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig();
assertEquals("model-google", config.getAlias());
assertEquals(GoogleIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(true, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(true, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals(GoogleIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(GoogleIdentityProvider.TOKEN_URL, config.getTokenUrl());
assertEquals(GoogleIdentityProvider.PROFILE_URL, config.getUserInfoUrl());
}
private void assertSamlIdentityProviderConfig(IdentityProviderModel identityProvider) {
SAMLIdentityProvider samlIdentityProvider = new SAMLIdentityProviderFactory().create(session, identityProvider);
SAMLIdentityProviderConfig config = samlIdentityProvider.getConfig();
assertEquals("model-saml-signed-idp", config.getAlias());
assertEquals(SAMLIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isStoreToken());
assertEquals("http://localhost:8082/auth/realms/realm-with-saml-identity-provider/protocol/saml", config.getSingleSignOnServiceUrl());
assertEquals("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", config.getNameIDPolicyFormat());
assertEquals("MIICwzCCAasCBgFlqZ1FNTANBgkqhkiG9w0BAQsFADAlMSMwIQYDVQQDDBpyZWFsbS13aXRoLXNhbWwtc2lnbmVkLWlkcDAeFw0xODA5MDUxMjAxMjFaFw0yODA5MDUxMjAzMDFaMCUxIzAhBgNVBAMMGnJlYWxtLXdpdGgtc2FtbC1zaWduZWQtaWRwMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgj8r0029eL0jJKXv6XbNj+QqsZO25HhZ0IjTEtb8mfh0tju/X8c6dXgILh5wU7OF00U+0mSYSE/+rrYKmY5g4oCleTe1+abavATP1tamtXGAUYqdutaXPrVn9yMsCWEPchSPZlEGq5iBJdA+xh9ejUmZJYXmln26HUVWq71/jC9GpjbRmFQ37f0X7WJoGyiqyttfKkKfUeBmRbX/0P0Zm6DVze8HjCDVPBllZE0a3HCgSF0rp0+s1xn7o91qdWKVattAVsGNjjDPz/sgwHOyyhDtSyajwXU+K/QUZ9pV4moGtwC9uIEymTylP7bu7qnxXIhfouEa+fEjAzTs0HJ5JQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQBRiW8PXdVr1aGaLrlVIJHvqQiPXh2/ZB+An0Ed7gH03mWGMiC63O3kisrhFGD8uS7YVlIxOfINyB1IT0XJ51Vxo0lWimcKTXzA7MjWlHoWnR9ZmvPiWZpjjAvyxl0nSqJWk2gtRD/PHNgJpqmISnyFqLIJqbr2Zk3Jv87j0CyPoUKMnSOXZYI+HQhgUJyY9CyyIVGrWTs21dkuG4Z9bYzcDYW3zPwt7zWgCd4wr/Gg2ZJeIpdlcfg30Dn2nkkDDpnEIEq/MtLam9Q1/f6T/XyaIEOyWDMDs62bvNtFlt0d4q2oOWJNyEYDAoSnx7x+/ac0Y8EYGRrNpmpiXwUxt2th", config.getSigningCertificate());
assertEquals(true, config.isWantAuthnRequestsSigned());
assertEquals(true, config.isForceAuthn());
assertEquals(true, config.isPostBindingAuthnRequest());
assertEquals(true, config.isPostBindingResponse());
assertEquals(true, config.isValidateSignature());
assertEquals(false, config.isAddExtensionsElementWithKeyInfo());
}
private void assertOidcIdentityProviderConfig(IdentityProviderModel identityProvider) {
OIDCIdentityProvider googleIdentityProvider = new OIDCIdentityProviderFactory().create(session, identityProvider);
OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig();
assertEquals("model-oidc-idp", config.getAlias());
assertEquals(OIDCIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(false, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
}
private void assertFacebookIdentityProviderConfig(RealmModel realm, IdentityProviderModel identityProvider) {
FacebookIdentityProvider facebookIdentityProvider = new FacebookIdentityProviderFactory().create(session, identityProvider);
OAuth2IdentityProviderConfig config = facebookIdentityProvider.getConfig();
assertEquals("model-facebook", config.getAlias());
assertEquals(FacebookIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals(realm.getBrowserFlow().getId(), identityProvider.getFirstBrokerLoginFlowId());
Assert.assertNull(identityProvider.getPostBrokerLoginFlowId());
assertEquals(FacebookIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(FacebookIdentityProvider.TOKEN_URL, config.getTokenUrl());
assertEquals(FacebookIdentityProvider.PROFILE_URL, config.getUserInfoUrl());
}
private void assertGitHubIdentityProviderConfig(RealmModel realm, IdentityProviderModel identityProvider) {
GitHubIdentityProvider gitHubIdentityProvider = new GitHubIdentityProviderFactory().create(session, identityProvider);
OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig();
assertEquals("model-github", config.getAlias());
assertEquals(GitHubIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals(realm.getFlowByAlias(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW).getId(), identityProvider.getFirstBrokerLoginFlowId());
assertEquals(realm.getBrowserFlow().getId(), identityProvider.getPostBrokerLoginFlowId());
assertEquals(GitHubIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(GitHubIdentityProvider.TOKEN_URL, config.getTokenUrl());
assertEquals(GitHubIdentityProvider.PROFILE_URL, config.getUserInfoUrl());
}
private void assertPayPalIdentityProviderConfig(RealmModel realm, IdentityProviderModel identityProvider) {
PayPalIdentityProvider payPalIdentityProvider = new PayPalIdentityProviderFactory().create(session, identityProvider);
PayPalIdentityProviderConfig config = payPalIdentityProvider.getConfig();
assertEquals("model-paypal", config.getAlias());
assertEquals(PayPalIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals(false, config.targetSandbox());
assertEquals(realm.getFlowByAlias(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW).getId(), identityProvider.getFirstBrokerLoginFlowId());
assertEquals(realm.getBrowserFlow().getId(), identityProvider.getPostBrokerLoginFlowId());
assertEquals(PayPalIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(PayPalIdentityProvider.BASE_URL + PayPalIdentityProvider.TOKEN_RESOURCE, config.getTokenUrl());
assertEquals(PayPalIdentityProvider.BASE_URL + PayPalIdentityProvider.PROFILE_RESOURCE, config.getUserInfoUrl());
}
private void assertLinkedInIdentityProviderConfig(IdentityProviderModel identityProvider) {
LinkedInIdentityProvider liIdentityProvider = new LinkedInIdentityProviderFactory().create(session, identityProvider);
OAuth2IdentityProviderConfig config = liIdentityProvider.getConfig();
assertEquals("model-linkedin", config.getAlias());
assertEquals(LinkedInIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals(LinkedInIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(LinkedInIdentityProvider.TOKEN_URL, config.getTokenUrl());
assertEquals(LinkedInIdentityProvider.PROFILE_URL, config.getUserInfoUrl());
}
private void assertStackoverflowIdentityProviderConfig(IdentityProviderModel identityProvider) {
StackoverflowIdentityProvider soIdentityProvider = new StackoverflowIdentityProviderFactory().create(session, identityProvider);
StackOverflowIdentityProviderConfig config = soIdentityProvider.getConfig();
assertEquals("model-stackoverflow", config.getAlias());
assertEquals(StackoverflowIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(false, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
assertEquals("keyValue", config.getKey());
assertEquals(StackoverflowIdentityProvider.AUTH_URL, config.getAuthorizationUrl());
assertEquals(StackoverflowIdentityProvider.TOKEN_URL, config.getTokenUrl());
assertEquals(StackoverflowIdentityProvider.PROFILE_URL, config.getUserInfoUrl());
}
private void assertOpenshiftIdentityProviderConfig(IdentityProviderModel identityProvider) {
OpenshiftV3IdentityProvider osoIdentityProvider = new OpenshiftV3IdentityProviderFactory().create(session, identityProvider);
OpenshiftV3IdentityProviderConfig config = osoIdentityProvider.getConfig();
assertEquals("model-openshift-v3", config.getAlias());
assertEquals(OpenshiftV3IdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(true, config.isStoreToken());
assertEquals(OpenshiftV3IdentityProvider.BASE_URL, config.getBaseUrl());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
}
private void assertTwitterIdentityProviderConfig(IdentityProviderModel identityProvider) {
TwitterIdentityProvider twitterIdentityProvider = new TwitterIdentityProviderFactory().create(session, identityProvider);
OAuth2IdentityProviderConfig config = twitterIdentityProvider.getConfig();
assertEquals("model-twitter", config.getAlias());
assertEquals(TwitterIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals(true, config.isEnabled());
assertEquals(false, config.isTrustEmail());
assertEquals(false, config.isAuthenticateByDefault());
assertEquals(true, config.isStoreToken());
assertEquals("clientId", config.getClientId());
assertEquals("clientSecret", config.getClientSecret());
}
private RealmModel installTestRealm() throws IOException {
RealmRepresentation realmRepresentation = loadJson("broker-test/test-realm-with-broker.json");
assertNotNull(realmRepresentation);
assertEquals("realm-with-broker", realmRepresentation.getRealm());
RealmModel realmModel = this.realmManager.getRealm("realm-with-broker");
if (realmModel == null) {
realmModel = this.realmManager.importRealm(realmRepresentation);
commit();
realmModel = this.realmManager.getRealm(realmModel.getId());
assertNotNull(realmModel);
}
return realmModel;
}
}