From 5fae76c7e4d76c92eebee95ff1118b5c9efd3dcb Mon Sep 17 00:00:00 2001 From: pedroigor Date: Thu, 29 Jan 2015 16:05:00 -0200 Subject: [PATCH] [KEYCLOAK-883] - Adding tests for update profile. Removing old social related classes. --- .../testsuite/DummySocialServlet.java | 77 ----- .../broker/AbstractIdentityProviderTest.java | 247 +++++++++++++--- .../broker/ImportIdentityProviderTest.java | 42 ++- .../OIDCKeyCloakServerBrokerBasicTest.java | 27 +- .../SAMLKeyCloakServerBrokerBasicTest.java | 25 +- ...KeyCloakServerBrokerWithSignatureTest.java | 25 +- .../testsuite/social/SocialLoginTest.java | 276 ------------------ ...on => test-broker-realm-with-kc-oidc.json} | 10 + ...broker-realm-with-saml-with-signature.json | 10 + .../test-broker-realm-with-saml.json | 10 + .../broker-test/test-realm-with-broker.json | 40 +-- 11 files changed, 324 insertions(+), 465 deletions(-) delete mode 100755 testsuite/integration/src/test/java/org/keycloak/testsuite/DummySocialServlet.java delete mode 100755 testsuite/integration/src/test/java/org/keycloak/testsuite/social/SocialLoginTest.java rename testsuite/integration/src/test/resources/broker-test/{test-broker-realm-with-oidc.json => test-broker-realm-with-kc-oidc.json} (90%) diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/DummySocialServlet.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/DummySocialServlet.java deleted file mode 100755 index fe2745c413..0000000000 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/DummySocialServlet.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.keycloak.testsuite; - -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URLEncodedUtils; -import org.keycloak.OAuth2Constants; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.util.List; -import java.util.UUID; - -public class DummySocialServlet extends HttpServlet { - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - PrintWriter pw = resp.getWriter(); - pw.print(""); - pw.print(""); - pw.print("
"); - pw.print(""); - pw.print(""); - pw.print(""); - pw.print(""); - pw.print(""); - pw.print(""); - pw.print(""); - pw.print("
"); - pw.print(""); - pw.print(""); - pw.flush(); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String state = null; - String redirectUri = null; - - List query = null; - try { - URI uri = URI.create(req.getRequestURL().append('?').append(req.getQueryString()).toString()); - query = URLEncodedUtils.parse(uri, "UTF-8"); - } catch (Exception e) { - throw new RuntimeException(e); - } - for (NameValuePair p : query) { - if (OAuth2Constants.STATE.equals(p.getName())) { - state = p.getValue(); - } else if (OAuth2Constants.REDIRECT_URI.equals(p.getName())) { - redirectUri = p.getValue(); - } - } - - String redirect; - if (req.getParameter("login") != null) { - redirect = redirectUri + "?id=" + req.getParameter("id") + "&username=" + req.getParameter("username") + "&state=" + state + "&code=" + UUID.randomUUID().toString(); - if (req.getParameter("firstname") != null) { - redirect += "&firstname=" + req.getParameter("firstname"); - } - if (req.getParameter("lastname") != null) { - redirect += "&lastname=" + req.getParameter("lastname"); - } - if (req.getParameter("email") != null) { - redirect += "&email=" + req.getParameter("email"); - } - } else { - redirect = redirectUri + "?error=access_denied&state=" + state; - } - - resp.sendRedirect(redirect); - } - -} diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/AbstractIdentityProviderTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/AbstractIdentityProviderTest.java index 1f79f8fd22..0367bb7d15 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/AbstractIdentityProviderTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/AbstractIdentityProviderTest.java @@ -18,11 +18,17 @@ package org.keycloak.testsuite.broker; import org.codehaus.jackson.map.ObjectMapper; +import org.junit.After; +import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; +import org.junit.Test; +import org.keycloak.models.FederatedIdentityModel; +import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; +import org.keycloak.representations.IDToken; import org.keycloak.services.managers.RealmManager; import org.keycloak.testsuite.broker.util.UserSessionStatusServlet; import org.keycloak.testsuite.broker.util.UserSessionStatusServlet.UserSessionStatus; @@ -31,11 +37,17 @@ import org.keycloak.testsuite.pages.LoginUpdateProfilePage; import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.WebResource; import org.keycloak.testsuite.rule.WebRule; +import org.openqa.selenium.By; +import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; import java.io.IOException; import java.net.URL; +import java.util.List; +import java.util.Set; +import static com.thoughtworks.selenium.SeleneseTestBase.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -73,76 +85,217 @@ public abstract class AbstractIdentityProviderTest { @WebResource private LoginUpdateProfilePage updateProfilePage; - protected void assertSuccessfulAuthentication(String providerId) { + private KeycloakSession session; + + @Before + public void onBefore() { + this.session = brokerServerRule.startSession(); + removeTestUsers(); + brokerServerRule.stopSession(this.session, true); + this.session = brokerServerRule.startSession(); + } + + @After + public void onAfter() { + brokerServerRule.stopSession(this.session, true); + } + + @Test + public void testSuccessfulAuthentication() { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + identityProviderModel.setUpdateProfileFirstLogin(true); + + assertSuccessfulAuthentication(identityProviderModel); + } + + @Test + public void testSuccessfulAuthenticationWithoutUpdateProfile() { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + identityProviderModel.setUpdateProfileFirstLogin(false); + + assertSuccessfulAuthentication(identityProviderModel); + } + + @Test + public void testDisabled() { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + identityProviderModel.setEnabled(false); + + this.driver.navigate().to("http://localhost:8081/test-app/"); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); + + try { + this.driver.findElement(By.className(getProviderId())); + fail("Provider [" + getProviderId() + "] not disabled."); + } catch (NoSuchElementException nsee) { + + } + } + + @Test + public void testUserAlreadyExistsWhenUpdatingProfile() { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + identityProviderModel.setUpdateProfileFirstLogin(true); + this.driver.navigate().to("http://localhost:8081/test-app/"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); // choose the identity provider - this.loginPage.clickSocial(providerId); + this.loginPage.clickSocial(getProviderId()); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/")); // log in to identity provider this.loginPage.login("test-user", "password"); - doAfterProviderAuthentication(providerId); + doAfterProviderAuthentication(); - doUpdateProfile(providerId); + this.updateProfilePage.assertCurrent(); + this.updateProfilePage.update("Test", "User", "psilva@redhat.com"); + + WebElement element = this.driver.findElement(By.className("kc-feedback-text")); + + assertNotNull(element); + + assertEquals("Email already exists", element.getText()); + + this.updateProfilePage.assertCurrent(); + this.updateProfilePage.update("Test", "User", "test-user@redhat.com"); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app")); + + UserModel federatedUser = getFederatedUser(); + + assertNotNull(federatedUser); + } + + @Test + public void testUserAlreadyExistsWhenNotUpdatingProfile() { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + identityProviderModel.setUpdateProfileFirstLogin(false); + + this.driver.navigate().to("http://localhost:8081/test-app/"); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); + + // choose the identity provider + this.loginPage.clickSocial(getProviderId()); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/")); + + // log in to identity provider + this.loginPage.login("pedroigor", "password"); + + doAfterProviderAuthentication(); + + WebElement element = this.driver.findElement(By.className("kc-feedback-text")); + + assertNotNull(element); + + assertEquals("User with email already exists. Please login to account management to link the account.", element.getText()); + } + + private void assertSuccessfulAuthentication(IdentityProviderModel identityProviderModel) { + driver.navigate().to("http://localhost:8081/test-app"); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); + + // choose the identity provider + this.loginPage.clickSocial(getProviderId()); + + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/")); + + // log in to identity provider + this.loginPage.login("test-user", "password"); + + doAfterProviderAuthentication(); + + if (identityProviderModel.isUpdateProfileFirstLogin()) { + String userEmail = "new@email.com"; + String userFirstName = "New first"; + String userLastName = "New last"; + + // update profile + this.updateProfilePage.assertCurrent(); + this.updateProfilePage.update(userFirstName, userLastName, userEmail); + } // authenticated and redirected to app - assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app/")); - assertNotNull(retrieveSessionStatus()); + assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app")); - doAssertFederatedUser(providerId); + UserModel federatedUser = getFederatedUser(); + + assertNotNull(federatedUser); + + doAssertFederatedUser(federatedUser); + + RealmModel realm = getRealm(); + + Set federatedIdentities = this.session.users().getFederatedIdentities(federatedUser, realm); + + assertEquals(1, federatedIdentities.size()); + + FederatedIdentityModel federatedIdentityModel = federatedIdentities.iterator().next(); + + assertEquals(getProviderId(), federatedIdentityModel.getIdentityProvider()); + assertEquals(federatedUser.getUsername(), federatedIdentityModel.getUserName()); driver.navigate().to("http://localhost:8081/test-app/logout"); - driver.navigate().to("http://localhost:8081/test-app/"); + driver.navigate().to("http://localhost:8081/test-app"); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login")); } - protected void doAssertFederatedUser(String providerId) { - String userEmail = "new@email.com"; - String userFirstName = "New first"; - String userLastName = "New last"; - UserModel federatedUser = getFederatedUser(); - - assertEquals(userEmail, federatedUser.getEmail()); - assertEquals(userFirstName, federatedUser.getFirstName()); - assertEquals(userLastName, federatedUser.getLastName()); - } - protected UserModel getFederatedUser() { + UserSessionStatus userSessionStatus = retrieveSessionStatus(); + IDToken idToken = userSessionStatus.getIdToken(); KeycloakSession samlServerSession = brokerServerRule.startSession(); RealmModel brokerRealm = samlServerSession.realms().getRealm("realm-with-broker"); - UserModel userModel = samlServerSession.users().getUserByUsername("test-user", brokerRealm); - if (userModel != null) { - return userModel; - } - - userModel = samlServerSession.users().getUserByEmail("test-user@localhost", brokerRealm); - - if (userModel == null) { - return samlServerSession.users().getUserByEmail("new@email.com", brokerRealm); - } - - return userModel; + return samlServerSession.users().getUserById(idToken.getSubject(), brokerRealm); } - protected void doUpdateProfile(String providerId) { - String userEmail = "new@email.com"; - String userFirstName = "New first"; - String userLastName = "New last"; + protected void doAfterProviderAuthentication() { - // update profile - this.updateProfilePage.assertCurrent(); - this.updateProfilePage.update(userFirstName, userLastName, userEmail); } - protected void doAfterProviderAuthentication(String providerId) { + protected abstract String getProviderId(); + protected IdentityProviderModel getIdentityProviderModel() { + IdentityProviderModel identityProviderModel = getRealm().getIdentityProviderById(getProviderId()); + + assertNotNull(identityProviderModel); + + return identityProviderModel; + } + + private RealmModel getRealm() { + return this.session.realms().getRealm("realm-with-broker"); + } + + protected void doAssertFederatedUser(UserModel federatedUser) { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + if (identityProviderModel.isUpdateProfileFirstLogin()) { + String userEmail = "new@email.com"; + String userFirstName = "New first"; + String userLastName = "New last"; + + assertEquals(userEmail, federatedUser.getEmail()); + assertEquals(userFirstName, federatedUser.getFirstName()); + assertEquals(userLastName, federatedUser.getLastName()); + } else { + assertEquals("test-user@localhost", federatedUser.getEmail()); + assertEquals("Test", federatedUser.getFirstName()); + assertEquals("User", federatedUser.getLastName()); + } } private UserSessionStatus retrieveSessionStatus() { @@ -160,4 +313,20 @@ public abstract class AbstractIdentityProviderTest { return sessionStatus; } + private void removeTestUsers() { + RealmModel realm = getRealm(); + List users = this.session.users().getUsers(realm); + + for (UserModel user : users) { + Set identities = this.session.users().getFederatedIdentities(user, realm); + + for (FederatedIdentityModel fedIdentity : identities) { + this.session.users().removeFederatedIdentity(realm, user, fedIdentity.getIdentityProvider()); + } + + if (!user.getUsername().equals("pedroigor")) { + this.session.users().removeUser(realm, user); + } + } + } } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/ImportIdentityProviderTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/ImportIdentityProviderTest.java index b4735429fc..d8e759460b 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/ImportIdentityProviderTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/ImportIdentityProviderTest.java @@ -60,14 +60,6 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes assertIdentityProviderConfig(realm.getIdentityProviders()); assertTrue(realm.isIdentityFederationEnabled()); - - this.realmManager.removeRealm(realm); - - commit(); - - realm = this.realmManager.getRealm(realm.getId()); - - assertNull(realm); } @Test @@ -141,9 +133,9 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes Set checkedProviders = new HashSet(getExpectedProviders()); for (IdentityProviderModel identityProvider : identityProviders) { - String providerId = identityProvider.getProviderId(); + if (identityProvider.getId().startsWith("model-")) { + String providerId = identityProvider.getProviderId(); - if (!identityProvider.getId().contains("kc-")) { if (SAMLIdentityProviderFactory.PROVIDER_ID.equals(providerId)) { assertSamlIdentityProviderConfig(identityProvider); } else if (GoogleIdentityProviderFactory.PROVIDER_ID.equals(providerId)) { @@ -156,10 +148,12 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes assertGitHubIdentityProviderConfig(identityProvider); } else if (TwitterIdentityProviderFactory.PROVIDER_ID.equals(providerId)) { assertTwitterIdentityProviderConfig(identityProvider); + } else { + continue; } - } - checkedProviders.remove(providerId); + checkedProviders.remove(providerId); + } } assertTrue(checkedProviders.isEmpty()); @@ -169,7 +163,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes GoogleIdentityProvider googleIdentityProvider = new GoogleIdentityProviderFactory().create(identityProvider); OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig(); - assertEquals("google", config.getId()); + assertEquals("model-google", config.getId()); assertEquals(GoogleIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("Google", config.getName()); assertEquals(true, config.isEnabled()); @@ -186,7 +180,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes SAMLIdentityProvider samlIdentityProvider = new SAMLIdentityProviderFactory().create(identityProvider); SAMLIdentityProviderConfig config = samlIdentityProvider.getConfig(); - assertEquals("saml-signed-idp", config.getId()); + assertEquals("model-saml-signed-idp", config.getId()); assertEquals(SAMLIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("SAML Signed IdP", config.getName()); assertEquals(true, config.isEnabled()); @@ -205,7 +199,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes OIDCIdentityProvider googleIdentityProvider = new OIDCIdentityProviderFactory().create(identityProvider); OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig(); - assertEquals("oidc-idp", config.getId()); + assertEquals("model-oidc-idp", config.getId()); assertEquals(OIDCIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("OIDC IdP", config.getName()); assertEquals(false, config.isEnabled()); @@ -218,7 +212,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes FacebookIdentityProvider facebookIdentityProvider = new FacebookIdentityProviderFactory().create(identityProvider); OAuth2IdentityProviderConfig config = facebookIdentityProvider.getConfig(); - assertEquals("facebook", config.getId()); + assertEquals("model-facebook", config.getId()); assertEquals(FacebookIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("Facebook", config.getName()); assertEquals(true, config.isEnabled()); @@ -234,7 +228,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes GitHubIdentityProvider gitHubIdentityProvider = new GitHubIdentityProviderFactory().create(identityProvider); OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig(); - assertEquals("github", config.getId()); + assertEquals("model-github", config.getId()); assertEquals(GitHubIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("GitHub", config.getName()); assertEquals(true, config.isEnabled()); @@ -250,7 +244,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes TwitterIdentityProvider gitHubIdentityProvider = new TwitterIdentityProviderFactory().create(identityProvider); OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig(); - assertEquals("twitter", config.getId()); + assertEquals("model-twitter", config.getId()); assertEquals(TwitterIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals("Twitter", config.getName()); assertEquals(true, config.isEnabled()); @@ -265,13 +259,17 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes assertNotNull(realmRepresentation); assertEquals("realm-with-broker", realmRepresentation.getRealm()); - RealmModel realmModel = this.realmManager.importRealm(realmRepresentation); + RealmModel realmModel = this.realmManager.getRealm("realm-with-broker"); - commit(); + if (realmModel == null) { + realmModel = this.realmManager.importRealm(realmRepresentation); - realmModel = this.realmManager.getRealm(realmModel.getId()); + commit(); - assertNotNull(realmModel); + realmModel = this.realmManager.getRealm(realmModel.getId()); + + assertNotNull(realmModel); + } return realmModel; } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java index 81c26c013a..011af1b30f 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/OIDCKeyCloakServerBrokerBasicTest.java @@ -1,19 +1,14 @@ package org.keycloak.testsuite.broker; import org.junit.ClassRule; -import org.junit.Test; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; -import org.keycloak.models.UserModel; import org.keycloak.services.managers.RealmManager; import org.keycloak.testsuite.pages.OAuthGrantPage; import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.WebResource; import org.keycloak.testutils.KeycloakServer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - /** * @author pedroigor */ @@ -29,36 +24,22 @@ public class OIDCKeyCloakServerBrokerBasicTest extends AbstractIdentityProviderT @Override protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) { - server.importRealm(getClass().getResourceAsStream("/broker-test/test-broker-realm-with-oidc.json")); + server.importRealm(getClass().getResourceAsStream("/broker-test/test-broker-realm-with-kc-oidc.json")); } }; @WebResource private OAuthGrantPage grantPage; - @Test - public void testSuccessfulAuthentication() { - assertSuccessfulAuthentication("kc-oidc-idp"); - } - @Override - protected void doAfterProviderAuthentication(String providerId) { + protected void doAfterProviderAuthentication() { // grant access to broker-app grantPage.assertCurrent(); grantPage.accept(); } @Override - protected void doUpdateProfile(String providerId) { - } - - @Override - protected void doAssertFederatedUser(String providerId) { - UserModel userModel = getFederatedUser(); - - assertNotNull(userModel); - assertEquals("test-user@localhost", userModel.getEmail()); - assertEquals("Test", userModel.getFirstName()); - assertEquals("User", userModel.getLastName()); + protected String getProviderId() { + return "kc-oidc-idp"; } } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerBasicTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerBasicTest.java index 0fcfb5fb44..b14328a4c2 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerBasicTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerBasicTest.java @@ -1,13 +1,17 @@ package org.keycloak.testsuite.broker; import org.junit.ClassRule; -import org.junit.Test; +import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; import org.keycloak.services.managers.RealmManager; import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testutils.KeycloakServer; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + /** * @author pedroigor */ @@ -27,8 +31,21 @@ public class SAMLKeyCloakServerBrokerBasicTest extends AbstractIdentityProviderT } }; - @Test - public void testSuccessfulAuthentication() { - assertSuccessfulAuthentication("kc-saml-idp-basic"); + @Override + protected String getProviderId() { + return "kc-saml-idp-basic"; + } + + @Override + protected void doAssertFederatedUser(UserModel federatedUser) { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + if (identityProviderModel.isUpdateProfileFirstLogin()) { + super.doAssertFederatedUser(federatedUser); + } else { + assertEquals("test-user@localhost", federatedUser.getEmail()); + assertNull(federatedUser.getFirstName()); + assertNull(federatedUser.getLastName()); + } } } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerWithSignatureTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerWithSignatureTest.java index 65c4642ae9..47ddb14d31 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerWithSignatureTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/broker/SAMLKeyCloakServerBrokerWithSignatureTest.java @@ -1,13 +1,17 @@ package org.keycloak.testsuite.broker; import org.junit.ClassRule; -import org.junit.Test; +import org.keycloak.models.IdentityProviderModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; import org.keycloak.services.managers.RealmManager; import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testutils.KeycloakServer; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + /** * @author pedroigor */ @@ -27,8 +31,21 @@ public class SAMLKeyCloakServerBrokerWithSignatureTest extends AbstractIdentityP } }; - @Test - public void testSuccessfulAuthentication() { - assertSuccessfulAuthentication("kc-saml-signed-idp"); + @Override + protected String getProviderId() { + return "kc-saml-signed-idp"; + } + + @Override + protected void doAssertFederatedUser(UserModel federatedUser) { + IdentityProviderModel identityProviderModel = getIdentityProviderModel(); + + if (identityProviderModel.isUpdateProfileFirstLogin()) { + super.doAssertFederatedUser(federatedUser); + } else { + assertEquals("test-user@localhost", federatedUser.getEmail()); + assertNull(federatedUser.getFirstName()); + assertNull(federatedUser.getLastName()); + } } } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/social/SocialLoginTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/social/SocialLoginTest.java deleted file mode 100755 index 830f05fbeb..0000000000 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/social/SocialLoginTest.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * JBoss, Home of Professional Open Source. - * Copyright 2012, Red Hat, Inc., and individual contributors - * as indicated by the @author tags. See the copyright.txt file in the - * distribution for a full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.keycloak.testsuite.social; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.keycloak.OAuth2Constants; -import org.keycloak.events.Details; -import org.keycloak.events.Event; -import org.keycloak.events.EventType; -import org.keycloak.models.RealmModel; -import org.keycloak.representations.AccessToken; -import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.services.managers.RealmManager; -import org.keycloak.testsuite.AssertEvents; -import org.keycloak.testsuite.DummySocialServlet; -import org.keycloak.testsuite.OAuthClient; -import org.keycloak.testsuite.OAuthClient.AccessTokenResponse; -import org.keycloak.testsuite.pages.AppPage; -import org.keycloak.testsuite.pages.AppPage.RequestType; -import org.keycloak.testsuite.pages.LoginPage; -import org.keycloak.testsuite.pages.LoginUpdateProfilePage; -import org.keycloak.testsuite.rule.KeycloakRule; -import org.keycloak.testsuite.rule.KeycloakRule.KeycloakSetup; -import org.keycloak.testsuite.rule.WebResource; -import org.keycloak.testsuite.rule.WebRule; -import org.openqa.selenium.By; -import org.openqa.selenium.WebDriver; - -import java.util.HashMap; - -/** - * @author Stian Thorgersen - */ -@Ignore("Refactor based on KEYCLOAK-883") -public class SocialLoginTest { - - @ClassRule - public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakSetup() { - @Override - public void config(RealmManager manager, RealmModel defaultRealm, RealmModel appRealm) { - HashMap socialConfig = new HashMap(); - socialConfig.put("dummy.key", "1234"); - socialConfig.put("dummy.secret", "1234"); - } - }); - - @Rule - public WebRule webRule = new WebRule(this); - - @WebResource - protected WebDriver driver; - - @WebResource - protected AppPage appPage; - - @WebResource - protected LoginPage loginPage; - - @WebResource - protected LoginUpdateProfilePage profilePage; - - @WebResource - protected OAuthClient oauth; - - @Rule - public AssertEvents events = new AssertEvents(keycloakRule); - - @BeforeClass - public static void before() { - keycloakRule.deployServlet("dummy-social", "/dummy-social", DummySocialServlet.class); - } - - @Test - public void loginSuccess() throws Exception { - loginPage.open(); - - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("id")).sendKeys("1"); - driver.findElement(By.id("username")).sendKeys("dummy-user1"); - driver.findElement(By.id("firstname")).sendKeys("Bob"); - driver.findElement(By.id("lastname")).sendKeys("Builder"); - driver.findElement(By.id("email")).sendKeys("bob@builder.com"); - driver.findElement(By.id("login")).click(); - - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - - String userId = events.expect(EventType.REGISTER) - .user(AssertEvents.isUUID()) - .detail(Details.EMAIL, "bob@builder.com") - .detail(Details.REGISTER_METHOD, "social@dummy") - .detail(Details.REDIRECT_URI, AssertEvents.DEFAULT_REDIRECT_URI) - .detail(Details.USERNAME, "1@dummy") - .session((String) null) - .assertEvent().getUserId(); - - Event loginEvent = events.expectSocialLogin() - .user(userId) - .detail(Details.USERNAME, "1@dummy") - .detail(Details.AUTH_METHOD, "social@dummy") - .assertEvent(); - - String sessionId = loginEvent.getSessionId(); - String codeId = loginEvent.getDetails().get(Details.CODE_ID); - - AccessTokenResponse response = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), "password"); - - events.expectCodeToToken(codeId, sessionId).user(userId).assertEvent(); - - AccessToken token = oauth.verifyToken(response.getAccessToken()); - Assert.assertEquals(36, token.getSubject().length()); - Assert.assertEquals(sessionId, token.getSessionState()); - - UserRepresentation profile = keycloakRule.getUserById("test", token.getSubject()); - Assert.assertEquals(36, profile.getUsername().length()); - - Assert.assertEquals("Bob", profile.getFirstName()); - Assert.assertEquals("Builder", profile.getLastName()); - Assert.assertEquals("bob@builder.com", profile.getEmail()); - - oauth.openLogout(); - - events.expectLogout(sessionId).user(userId).assertEvent(); - - loginPage.open(); - - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("id")).sendKeys("1"); - driver.findElement(By.id("username")).sendKeys("dummy-user1"); - driver.findElement(By.id("login")).click(); - - events.expectSocialLogin().user(userId).detail(Details.USERNAME, "1@dummy").detail(Details.AUTH_METHOD, "social@dummy").assertEvent(); - } - - @Test - public void loginEmailExists() throws Exception { - loginPage.open(); - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("id")).sendKeys("loginEmailExists1"); - driver.findElement(By.id("username")).sendKeys("dummy-user1"); - driver.findElement(By.id("firstname")).sendKeys("Bob"); - driver.findElement(By.id("lastname")).sendKeys("Builder"); - driver.findElement(By.id("email")).sendKeys("loginEmailExists@builder.com"); - driver.findElement(By.id("login")).click(); - - oauth.openLogout(); - events.clear(); - - loginPage.open(); - - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("id")).sendKeys("loginEmailExists2"); - driver.findElement(By.id("username")).sendKeys("dummy-user2"); - driver.findElement(By.id("firstname")).sendKeys("Bob2"); - driver.findElement(By.id("lastname")).sendKeys("Builder2"); - driver.findElement(By.id("email")).sendKeys("loginEmailExists@builder.com"); - driver.findElement(By.id("login")).click(); - - Assert.assertTrue(loginPage.isCurrent()); - Assert.assertEquals("User with email already exists. Please login to account management to link the account.", loginPage.getError()); - - events.clear(); - } - - @Test - public void loginCancelled() throws Exception { - loginPage.open(); - - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("cancel")).click(); - - Assert.assertTrue(loginPage.isCurrent()); - Assert.assertEquals("Access denied", loginPage.getWarning()); - - events.expectSocialLogin().error("rejected_by_user").user((String) null).session((String) null).detail(Details.AUTH_METHOD, "social@dummy").removeDetail(Details.USERNAME).removeDetail(Details.CODE_ID).assertEvent(); - - String src = driver.getPageSource(); - loginPage.login("test-user@localhost", "password"); - - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - - events.expectLogin().assertEvent(); - } - - @Test - public void profileUpdateRequired() { - keycloakRule.configure(new KeycloakSetup() { - @Override - public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { - } - }); - - try { - loginPage.open(); - - loginPage.clickSocial("dummy"); - - driver.findElement(By.id("id")).sendKeys("2"); - driver.findElement(By.id("username")).sendKeys("dummy-user2"); - driver.findElement(By.id("firstname")).sendKeys("Bob"); - driver.findElement(By.id("lastname")).sendKeys("Builder"); - driver.findElement(By.id("email")).sendKeys("bob@builder.com"); - driver.findElement(By.id("login")).click(); - - profilePage.isCurrent(); - - Assert.assertEquals("Bob", profilePage.getFirstName()); - Assert.assertEquals("Builder", profilePage.getLastName()); - Assert.assertEquals("bob@builder.com", profilePage.getEmail()); - - String userId = events.expect(EventType.REGISTER) - .user(AssertEvents.isUUID()) - .detail(Details.EMAIL, "bob@builder.com") - .detail(Details.REGISTER_METHOD, "social@dummy") - .detail(Details.REDIRECT_URI, AssertEvents.DEFAULT_REDIRECT_URI) - .detail(Details.USERNAME, "2@dummy") - .assertEvent().getUserId(); - - profilePage.update("Dummy", "User", "dummy-user-reg@dummy-social"); - - events.expectRequiredAction(EventType.UPDATE_PROFILE).user(userId).detail(Details.AUTH_METHOD, "social@dummy").detail(Details.USERNAME, "2@dummy").assertEvent(); - events.expectRequiredAction(EventType.UPDATE_EMAIL).user(userId).detail(Details.AUTH_METHOD, "social@dummy").detail(Details.USERNAME, "2@dummy").detail(Details.PREVIOUS_EMAIL, "bob@builder.com").detail(Details.UPDATED_EMAIL, "dummy-user-reg@dummy-social").assertEvent(); - - Assert.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); - - Event loginEvent = events.expectLogin().user(userId).removeDetail(Details.USERNAME).detail(Details.AUTH_METHOD, "social@dummy").detail(Details.USERNAME, "2@dummy").assertEvent(); - String codeId = loginEvent.getDetails().get(Details.CODE_ID); - - AccessTokenResponse response = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), "password"); - AccessToken token = oauth.verifyToken(response.getAccessToken()); - - events.expectCodeToToken(codeId, loginEvent.getSessionId()).user(userId).assertEvent(); - - UserRepresentation profile = keycloakRule.getUserById("test", token.getSubject()); - - Assert.assertEquals("Dummy", profile.getFirstName()); - Assert.assertEquals("User", profile.getLastName()); - Assert.assertEquals("dummy-user-reg@dummy-social", profile.getEmail()); - } finally { - keycloakRule.configure(new KeycloakSetup() { - @Override - public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) { - } - }); - } - } - -} diff --git a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-oidc.json b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-kc-oidc.json similarity index 90% rename from testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-oidc.json rename to testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-kc-oidc.json index 6d7b9285db..d7831a7377 100755 --- a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-oidc.json +++ b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-kc-oidc.json @@ -33,6 +33,16 @@ "value" : "password" } ], "realmRoles": ["manager"] + }, + { + "username" : "pedroigor", + "enabled": true, + "email" : "psilva@redhat.com", + "credentials" : [ + { "type" : "password", + "value" : "password" } + ], + "realmRoles": ["manager"] } ], "roles" : { diff --git a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml-with-signature.json b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml-with-signature.json index 9882b81739..82db4ea508 100755 --- a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml-with-signature.json +++ b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml-with-signature.json @@ -36,6 +36,16 @@ "value" : "password" } ], "realmRoles": ["manager"] + }, + { + "username" : "pedroigor", + "enabled": true, + "email" : "psilva@redhat.com", + "credentials" : [ + { "type" : "password", + "value" : "password" } + ], + "realmRoles": ["manager"] } ], "roles" : { diff --git a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml.json b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml.json index 3f6d27a05c..4bf96ff71d 100755 --- a/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml.json +++ b/testsuite/integration/src/test/resources/broker-test/test-broker-realm-with-saml.json @@ -30,6 +30,16 @@ "value" : "password" } ], "realmRoles": ["manager"] + }, + { + "username" : "pedroigor", + "enabled": true, + "email" : "psilva@redhat.com", + "credentials" : [ + { "type" : "password", + "value" : "password" } + ], + "realmRoles": ["manager"] } ], "roles" : { diff --git a/testsuite/integration/src/test/resources/broker-test/test-realm-with-broker.json b/testsuite/integration/src/test/resources/broker-test/test-realm-with-broker.json index f86c74d0d9..d5865c1417 100755 --- a/testsuite/integration/src/test/resources/broker-test/test-realm-with-broker.json +++ b/testsuite/integration/src/test/resources/broker-test/test-realm-with-broker.json @@ -8,7 +8,7 @@ "publicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgj8r0029eL0jJKXv6XbNj+QqsZO25HhZ0IjTEtb8mfh0tju/X8c6dXgILh5wU7OF00U+0mSYSE/+rrYKmY5g4oCleTe1+abavATP1tamtXGAUYqdutaXPrVn9yMsCWEPchSPZlEGq5iBJdA+xh9ejUmZJYXmln26HUVWq71/jC9GpjbRmFQ37f0X7WJoGyiqyttfKkKfUeBmRbX/0P0Zm6DVze8HjCDVPBllZE0a3HCgSF0rp0+s1xn7o91qdWKVattAVsGNjjDPz/sgwHOyyhDtSyajwXU+K/QUZ9pV4moGtwC9uIEymTylP7bu7qnxXIhfouEa+fEjAzTs0HJ5JQIDAQAB", "identityProviders" : [ { - "id" : "google", + "id" : "model-google", "providerId" : "google", "name" : "Google", "enabled": true, @@ -19,7 +19,7 @@ } }, { - "id" : "facebook", + "id" : "model-facebook", "providerId" : "facebook", "name" : "Facebook", "enabled": true, @@ -33,7 +33,7 @@ } }, { - "id" : "github", + "id" : "model-github", "providerId" : "github", "name" : "GitHub", "enabled": true, @@ -47,7 +47,7 @@ } }, { - "id" : "twitter", + "id" : "model-twitter", "providerId" : "twitter", "name" : "Twitter", "enabled": true, @@ -61,7 +61,7 @@ } }, { - "id" : "saml-signed-idp", + "id" : "model-saml-signed-idp", "providerId" : "saml", "name" : "SAML Signed IdP", "enabled": true, @@ -109,7 +109,7 @@ } }, { - "id" : "oidc-idp", + "id" : "model-oidc-idp", "providerId" : "oidc", "name" : "OIDC IdP", "enabled": false, @@ -125,20 +125,20 @@ } }, { - "id" : "kc-oidc-idp", - "providerId" : "oidc", - "name" : "KeyCloak OIDC IdP", - "enabled": true, - "updateProfileFirstLogin" : "false", - "config": { - "clientId": "broker-app", - "clientSecret": "secret", - "prompt": "login", - "authorizationUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/tokens/login", - "tokenUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/protocol/openid-connect/access/codes", - "userInfoUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/protocol/openid-connect/userinfo", - "defaultScope": "email profile" - } + "id" : "kc-oidc-idp", + "providerId" : "oidc", + "name" : "KeyCloak OIDC IdP", + "enabled": true, + "updateProfileFirstLogin" : "false", + "config": { + "clientId": "broker-app", + "clientSecret": "secret", + "prompt": "login", + "authorizationUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/tokens/login", + "tokenUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/protocol/openid-connect/access/codes", + "userInfoUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/protocol/openid-connect/userinfo", + "defaultScope": "email profile" + } } ], "users": [