[KEYCLOAK-883] - Adding tests for update profile. Removing old social related classes.

This commit is contained in:
pedroigor 2015-01-29 16:05:00 -02:00
parent 8fc6368202
commit 5fae76c7e4
11 changed files with 324 additions and 465 deletions

View file

@ -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("<html>");
pw.print("<body>");
pw.print("<form method=\"post\">");
pw.print("<label for=\"id\">ID</label><input type=\"text\" id=\"id\" name=\"id\" />");
pw.print("<label for=\"username\">Username</label><input type=\"text\" id=\"username\" name=\"username\" />");
pw.print("<label for=\"firstname\">First Name</label><input type=\"text\" id=\"firstname\" name=\"firstname\" />");
pw.print("<label for=\"lastname\">Last Name</label><input type=\"text\" id=\"lastname\" name=\"lastname\" />");
pw.print("<label for=\"email\">Email</label><input type=\"text\" id=\"email\" name=\"email\" />");
pw.print("<input type=\"submit\" id=\"login\" name=\"login\" value=\"login\" />");
pw.print("<input type=\"submit\" id=\"cancel\" name=\"cancel\" value=\"cancel\" />");
pw.print("</form>");
pw.print("</body>");
pw.print("</html>");
pw.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String state = null;
String redirectUri = null;
List<NameValuePair> 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);
}
}

View file

@ -18,11 +18,17 @@
package org.keycloak.testsuite.broker; package org.keycloak.testsuite.broker;
import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Rule; 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.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.representations.IDToken;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.broker.util.UserSessionStatusServlet; import org.keycloak.testsuite.broker.util.UserSessionStatusServlet;
import org.keycloak.testsuite.broker.util.UserSessionStatusServlet.UserSessionStatus; 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.AbstractKeycloakRule;
import org.keycloak.testsuite.rule.WebResource; import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule; 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.WebDriver;
import org.openqa.selenium.WebElement;
import java.io.IOException; import java.io.IOException;
import java.net.URL; 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.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@ -73,76 +85,217 @@ public abstract class AbstractIdentityProviderTest {
@WebResource @WebResource
private LoginUpdateProfilePage updateProfilePage; 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/"); 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")); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/auth/realms/realm-with-broker/protocol/openid-connect/login"));
// choose the identity provider // choose the identity provider
this.loginPage.clickSocial(providerId); this.loginPage.clickSocial(getProviderId());
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/")); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8082/auth/"));
// log in to identity provider // log in to identity provider
this.loginPage.login("test-user", "password"); 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 // authenticated and redirected to app
assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app/")); assertTrue(this.driver.getCurrentUrl().startsWith("http://localhost:8081/test-app"));
assertNotNull(retrieveSessionStatus());
doAssertFederatedUser(providerId); UserModel federatedUser = getFederatedUser();
assertNotNull(federatedUser);
doAssertFederatedUser(federatedUser);
RealmModel realm = getRealm();
Set<FederatedIdentityModel> 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/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")); 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() { protected UserModel getFederatedUser() {
UserSessionStatus userSessionStatus = retrieveSessionStatus();
IDToken idToken = userSessionStatus.getIdToken();
KeycloakSession samlServerSession = brokerServerRule.startSession(); KeycloakSession samlServerSession = brokerServerRule.startSession();
RealmModel brokerRealm = samlServerSession.realms().getRealm("realm-with-broker"); RealmModel brokerRealm = samlServerSession.realms().getRealm("realm-with-broker");
UserModel userModel = samlServerSession.users().getUserByUsername("test-user", brokerRealm);
if (userModel != null) { return samlServerSession.users().getUserById(idToken.getSubject(), brokerRealm);
return userModel;
}
userModel = samlServerSession.users().getUserByEmail("test-user@localhost", brokerRealm);
if (userModel == null) {
return samlServerSession.users().getUserByEmail("new@email.com", brokerRealm);
}
return userModel;
} }
protected void doUpdateProfile(String providerId) { protected void doAfterProviderAuthentication() {
String userEmail = "new@email.com";
String userFirstName = "New first";
String userLastName = "New last";
// 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() { private UserSessionStatus retrieveSessionStatus() {
@ -160,4 +313,20 @@ public abstract class AbstractIdentityProviderTest {
return sessionStatus; return sessionStatus;
} }
private void removeTestUsers() {
RealmModel realm = getRealm();
List<UserModel> users = this.session.users().getUsers(realm);
for (UserModel user : users) {
Set<FederatedIdentityModel> 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);
}
}
}
} }

View file

@ -60,14 +60,6 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
assertIdentityProviderConfig(realm.getIdentityProviders()); assertIdentityProviderConfig(realm.getIdentityProviders());
assertTrue(realm.isIdentityFederationEnabled()); assertTrue(realm.isIdentityFederationEnabled());
this.realmManager.removeRealm(realm);
commit();
realm = this.realmManager.getRealm(realm.getId());
assertNull(realm);
} }
@Test @Test
@ -141,9 +133,9 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
Set<String> checkedProviders = new HashSet<String>(getExpectedProviders()); Set<String> checkedProviders = new HashSet<String>(getExpectedProviders());
for (IdentityProviderModel identityProvider : identityProviders) { 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)) { if (SAMLIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertSamlIdentityProviderConfig(identityProvider); assertSamlIdentityProviderConfig(identityProvider);
} else if (GoogleIdentityProviderFactory.PROVIDER_ID.equals(providerId)) { } else if (GoogleIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
@ -156,10 +148,12 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
assertGitHubIdentityProviderConfig(identityProvider); assertGitHubIdentityProviderConfig(identityProvider);
} else if (TwitterIdentityProviderFactory.PROVIDER_ID.equals(providerId)) { } else if (TwitterIdentityProviderFactory.PROVIDER_ID.equals(providerId)) {
assertTwitterIdentityProviderConfig(identityProvider); assertTwitterIdentityProviderConfig(identityProvider);
} else {
continue;
} }
}
checkedProviders.remove(providerId); checkedProviders.remove(providerId);
}
} }
assertTrue(checkedProviders.isEmpty()); assertTrue(checkedProviders.isEmpty());
@ -169,7 +163,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
GoogleIdentityProvider googleIdentityProvider = new GoogleIdentityProviderFactory().create(identityProvider); GoogleIdentityProvider googleIdentityProvider = new GoogleIdentityProviderFactory().create(identityProvider);
OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig(); OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig();
assertEquals("google", config.getId()); assertEquals("model-google", config.getId());
assertEquals(GoogleIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(GoogleIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("Google", config.getName()); assertEquals("Google", config.getName());
assertEquals(true, config.isEnabled()); assertEquals(true, config.isEnabled());
@ -186,7 +180,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
SAMLIdentityProvider samlIdentityProvider = new SAMLIdentityProviderFactory().create(identityProvider); SAMLIdentityProvider samlIdentityProvider = new SAMLIdentityProviderFactory().create(identityProvider);
SAMLIdentityProviderConfig config = samlIdentityProvider.getConfig(); SAMLIdentityProviderConfig config = samlIdentityProvider.getConfig();
assertEquals("saml-signed-idp", config.getId()); assertEquals("model-saml-signed-idp", config.getId());
assertEquals(SAMLIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(SAMLIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("SAML Signed IdP", config.getName()); assertEquals("SAML Signed IdP", config.getName());
assertEquals(true, config.isEnabled()); assertEquals(true, config.isEnabled());
@ -205,7 +199,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
OIDCIdentityProvider googleIdentityProvider = new OIDCIdentityProviderFactory().create(identityProvider); OIDCIdentityProvider googleIdentityProvider = new OIDCIdentityProviderFactory().create(identityProvider);
OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig(); OIDCIdentityProviderConfig config = googleIdentityProvider.getConfig();
assertEquals("oidc-idp", config.getId()); assertEquals("model-oidc-idp", config.getId());
assertEquals(OIDCIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(OIDCIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("OIDC IdP", config.getName()); assertEquals("OIDC IdP", config.getName());
assertEquals(false, config.isEnabled()); assertEquals(false, config.isEnabled());
@ -218,7 +212,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
FacebookIdentityProvider facebookIdentityProvider = new FacebookIdentityProviderFactory().create(identityProvider); FacebookIdentityProvider facebookIdentityProvider = new FacebookIdentityProviderFactory().create(identityProvider);
OAuth2IdentityProviderConfig config = facebookIdentityProvider.getConfig(); OAuth2IdentityProviderConfig config = facebookIdentityProvider.getConfig();
assertEquals("facebook", config.getId()); assertEquals("model-facebook", config.getId());
assertEquals(FacebookIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(FacebookIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("Facebook", config.getName()); assertEquals("Facebook", config.getName());
assertEquals(true, config.isEnabled()); assertEquals(true, config.isEnabled());
@ -234,7 +228,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
GitHubIdentityProvider gitHubIdentityProvider = new GitHubIdentityProviderFactory().create(identityProvider); GitHubIdentityProvider gitHubIdentityProvider = new GitHubIdentityProviderFactory().create(identityProvider);
OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig(); OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig();
assertEquals("github", config.getId()); assertEquals("model-github", config.getId());
assertEquals(GitHubIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(GitHubIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("GitHub", config.getName()); assertEquals("GitHub", config.getName());
assertEquals(true, config.isEnabled()); assertEquals(true, config.isEnabled());
@ -250,7 +244,7 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
TwitterIdentityProvider gitHubIdentityProvider = new TwitterIdentityProviderFactory().create(identityProvider); TwitterIdentityProvider gitHubIdentityProvider = new TwitterIdentityProviderFactory().create(identityProvider);
OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig(); OAuth2IdentityProviderConfig config = gitHubIdentityProvider.getConfig();
assertEquals("twitter", config.getId()); assertEquals("model-twitter", config.getId());
assertEquals(TwitterIdentityProviderFactory.PROVIDER_ID, config.getProviderId()); assertEquals(TwitterIdentityProviderFactory.PROVIDER_ID, config.getProviderId());
assertEquals("Twitter", config.getName()); assertEquals("Twitter", config.getName());
assertEquals(true, config.isEnabled()); assertEquals(true, config.isEnabled());
@ -265,13 +259,17 @@ public class ImportIdentityProviderTest extends AbstractIdentityProviderModelTes
assertNotNull(realmRepresentation); assertNotNull(realmRepresentation);
assertEquals("realm-with-broker", realmRepresentation.getRealm()); 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; return realmModel;
} }

View file

@ -1,19 +1,14 @@
package org.keycloak.testsuite.broker; package org.keycloak.testsuite.broker;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.pages.OAuthGrantPage; import org.keycloak.testsuite.pages.OAuthGrantPage;
import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testsuite.rule.WebResource; import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testutils.KeycloakServer; import org.keycloak.testutils.KeycloakServer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** /**
* @author pedroigor * @author pedroigor
*/ */
@ -29,36 +24,22 @@ public class OIDCKeyCloakServerBrokerBasicTest extends AbstractIdentityProviderT
@Override @Override
protected void configure(KeycloakSession session, RealmManager manager, RealmModel adminRealm) { 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 @WebResource
private OAuthGrantPage grantPage; private OAuthGrantPage grantPage;
@Test
public void testSuccessfulAuthentication() {
assertSuccessfulAuthentication("kc-oidc-idp");
}
@Override @Override
protected void doAfterProviderAuthentication(String providerId) { protected void doAfterProviderAuthentication() {
// grant access to broker-app // grant access to broker-app
grantPage.assertCurrent(); grantPage.assertCurrent();
grantPage.accept(); grantPage.accept();
} }
@Override @Override
protected void doUpdateProfile(String providerId) { protected String getProviderId() {
} return "kc-oidc-idp";
@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());
} }
} }

View file

@ -1,13 +1,17 @@
package org.keycloak.testsuite.broker; package org.keycloak.testsuite.broker;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test; import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testutils.KeycloakServer; import org.keycloak.testutils.KeycloakServer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/** /**
* @author pedroigor * @author pedroigor
*/ */
@ -27,8 +31,21 @@ public class SAMLKeyCloakServerBrokerBasicTest extends AbstractIdentityProviderT
} }
}; };
@Test @Override
public void testSuccessfulAuthentication() { protected String getProviderId() {
assertSuccessfulAuthentication("kc-saml-idp-basic"); 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());
}
} }
} }

View file

@ -1,13 +1,17 @@
package org.keycloak.testsuite.broker; package org.keycloak.testsuite.broker;
import org.junit.ClassRule; import org.junit.ClassRule;
import org.junit.Test; import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.managers.RealmManager; import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.rule.AbstractKeycloakRule; import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testutils.KeycloakServer; import org.keycloak.testutils.KeycloakServer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/** /**
* @author pedroigor * @author pedroigor
*/ */
@ -27,8 +31,21 @@ public class SAMLKeyCloakServerBrokerWithSignatureTest extends AbstractIdentityP
} }
}; };
@Test @Override
public void testSuccessfulAuthentication() { protected String getProviderId() {
assertSuccessfulAuthentication("kc-saml-signed-idp"); 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());
}
} }
} }

View file

@ -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 <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
@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<String, String> socialConfig = new HashMap<String, String>();
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) {
}
});
}
}
}

View file

@ -33,6 +33,16 @@
"value" : "password" } "value" : "password" }
], ],
"realmRoles": ["manager"] "realmRoles": ["manager"]
},
{
"username" : "pedroigor",
"enabled": true,
"email" : "psilva@redhat.com",
"credentials" : [
{ "type" : "password",
"value" : "password" }
],
"realmRoles": ["manager"]
} }
], ],
"roles" : { "roles" : {

View file

@ -36,6 +36,16 @@
"value" : "password" } "value" : "password" }
], ],
"realmRoles": ["manager"] "realmRoles": ["manager"]
},
{
"username" : "pedroigor",
"enabled": true,
"email" : "psilva@redhat.com",
"credentials" : [
{ "type" : "password",
"value" : "password" }
],
"realmRoles": ["manager"]
} }
], ],
"roles" : { "roles" : {

View file

@ -30,6 +30,16 @@
"value" : "password" } "value" : "password" }
], ],
"realmRoles": ["manager"] "realmRoles": ["manager"]
},
{
"username" : "pedroigor",
"enabled": true,
"email" : "psilva@redhat.com",
"credentials" : [
{ "type" : "password",
"value" : "password" }
],
"realmRoles": ["manager"]
} }
], ],
"roles" : { "roles" : {

View file

@ -8,7 +8,7 @@
"publicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgj8r0029eL0jJKXv6XbNj+QqsZO25HhZ0IjTEtb8mfh0tju/X8c6dXgILh5wU7OF00U+0mSYSE/+rrYKmY5g4oCleTe1+abavATP1tamtXGAUYqdutaXPrVn9yMsCWEPchSPZlEGq5iBJdA+xh9ejUmZJYXmln26HUVWq71/jC9GpjbRmFQ37f0X7WJoGyiqyttfKkKfUeBmRbX/0P0Zm6DVze8HjCDVPBllZE0a3HCgSF0rp0+s1xn7o91qdWKVattAVsGNjjDPz/sgwHOyyhDtSyajwXU+K/QUZ9pV4moGtwC9uIEymTylP7bu7qnxXIhfouEa+fEjAzTs0HJ5JQIDAQAB", "publicKey": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgj8r0029eL0jJKXv6XbNj+QqsZO25HhZ0IjTEtb8mfh0tju/X8c6dXgILh5wU7OF00U+0mSYSE/+rrYKmY5g4oCleTe1+abavATP1tamtXGAUYqdutaXPrVn9yMsCWEPchSPZlEGq5iBJdA+xh9ejUmZJYXmln26HUVWq71/jC9GpjbRmFQ37f0X7WJoGyiqyttfKkKfUeBmRbX/0P0Zm6DVze8HjCDVPBllZE0a3HCgSF0rp0+s1xn7o91qdWKVattAVsGNjjDPz/sgwHOyyhDtSyajwXU+K/QUZ9pV4moGtwC9uIEymTylP7bu7qnxXIhfouEa+fEjAzTs0HJ5JQIDAQAB",
"identityProviders" : [ "identityProviders" : [
{ {
"id" : "google", "id" : "model-google",
"providerId" : "google", "providerId" : "google",
"name" : "Google", "name" : "Google",
"enabled": true, "enabled": true,
@ -19,7 +19,7 @@
} }
}, },
{ {
"id" : "facebook", "id" : "model-facebook",
"providerId" : "facebook", "providerId" : "facebook",
"name" : "Facebook", "name" : "Facebook",
"enabled": true, "enabled": true,
@ -33,7 +33,7 @@
} }
}, },
{ {
"id" : "github", "id" : "model-github",
"providerId" : "github", "providerId" : "github",
"name" : "GitHub", "name" : "GitHub",
"enabled": true, "enabled": true,
@ -47,7 +47,7 @@
} }
}, },
{ {
"id" : "twitter", "id" : "model-twitter",
"providerId" : "twitter", "providerId" : "twitter",
"name" : "Twitter", "name" : "Twitter",
"enabled": true, "enabled": true,
@ -61,7 +61,7 @@
} }
}, },
{ {
"id" : "saml-signed-idp", "id" : "model-saml-signed-idp",
"providerId" : "saml", "providerId" : "saml",
"name" : "SAML Signed IdP", "name" : "SAML Signed IdP",
"enabled": true, "enabled": true,
@ -109,7 +109,7 @@
} }
}, },
{ {
"id" : "oidc-idp", "id" : "model-oidc-idp",
"providerId" : "oidc", "providerId" : "oidc",
"name" : "OIDC IdP", "name" : "OIDC IdP",
"enabled": false, "enabled": false,
@ -125,20 +125,20 @@
} }
}, },
{ {
"id" : "kc-oidc-idp", "id" : "kc-oidc-idp",
"providerId" : "oidc", "providerId" : "oidc",
"name" : "KeyCloak OIDC IdP", "name" : "KeyCloak OIDC IdP",
"enabled": true, "enabled": true,
"updateProfileFirstLogin" : "false", "updateProfileFirstLogin" : "false",
"config": { "config": {
"clientId": "broker-app", "clientId": "broker-app",
"clientSecret": "secret", "clientSecret": "secret",
"prompt": "login", "prompt": "login",
"authorizationUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/tokens/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", "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", "userInfoUrl": "http://localhost:8082/auth/realms/realm-with-oidc-identity-provider/protocol/openid-connect/userinfo",
"defaultScope": "email profile" "defaultScope": "email profile"
} }
} }
], ],
"users": [ "users": [