Merge pull request #296 from patriot1burke/master

adapter testing
This commit is contained in:
Bill Burke 2014-03-13 21:48:14 -04:00
commit e03737c665
13 changed files with 423 additions and 8 deletions

View file

@ -108,7 +108,7 @@ public abstract class OAuthRequestAuthenticator {
protected String getRedirectUri(String state) {
String url = getRequestUrl();
log.infof("sending redirect uri: %s", url);
log.infof("callback uri: %s", url);
if (!isRequestSecure() && deployment.isSslRequired()) {
int port = sslRedirectPort();
if (port < 0) {
@ -147,6 +147,7 @@ public abstract class OAuthRequestAuthenticator {
exchange.getResponse().setStatus(403);
return true;
}
log.info("Sending redirect to login page: " + redirect);
exchange.getResponse().setStatus(302);
exchange.getResponse().setCookie(deployment.getStateCookieName(), state, /* need to set path? */ null, null, -1, deployment.isSslRequired(), false);
exchange.getResponse().setHeader("Location", redirect);

View file

@ -19,6 +19,8 @@ import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import javax.servlet.ServletContext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;
@ -43,7 +45,7 @@ public class KeycloakServletExtension implements ServletExtension {
return false;
}
private InputStream getJSONFromServletContext(ServletContext servletContext) {
private static InputStream getJSONFromServletContext(ServletContext servletContext) {
String json = servletContext.getInitParameter(AdapterConstants.AUTH_DATA_PARAM_NAME);
if (json == null) {
return null;
@ -51,6 +53,25 @@ public class KeycloakServletExtension implements ServletExtension {
return new ByteArrayInputStream(json.getBytes());
}
private static InputStream getConfigInputStream(ServletContext context) {
InputStream is = getJSONFromServletContext(context);
if (is == null) {
String path = context.getInitParameter("keycloak.config.file");
if (path == null) {
log.info("**** using /WEB-INF/keycloak.json");
is = context.getResourceAsStream("/WEB-INF/keycloak.json");
} else {
try {
is = new FileInputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
}
return is;
}
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK")) {
@ -58,10 +79,7 @@ public class KeycloakServletExtension implements ServletExtension {
return;
}
log.info("KeycloakServletException initialization");
InputStream is = getJSONFromServletContext(servletContext);
if (is == null) {
is = servletContext.getResourceAsStream("/WEB-INF/keycloak.json");
}
InputStream is = getConfigInputStream(servletContext);
if (is == null) throw new RuntimeException("Unable to find realm config in /WEB-INF/keycloak.json or in keycloak subsystem.");
KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(is);
UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement(deployment);

View file

@ -46,8 +46,10 @@ public class ServletKeycloakAuthMech implements AuthenticationMechanism {
}
protected ServletRequestAuthenticator createRequestAuthenticator(HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
int confidentialPort = 8443;
if (portManager != null) confidentialPort = portManager.getConfidentialPort(exchange);
return new ServletRequestAuthenticator(facade, deployment,
portManager.getConfidentialPort(exchange), securityContext, exchange, userSessionManagement);
confidentialPort, securityContext, exchange, userSessionManagement);
}
@Override

View file

@ -66,6 +66,17 @@
<artifactId>keycloak-js-adapter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-undertow-adapter</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
</dependency>
<!--
<dependency>
<groupId>org.keycloak</groupId>

View file

@ -0,0 +1,105 @@
/*
* 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.adapter;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.services.managers.RealmManager;
import org.keycloak.testsuite.OAuthClient;
import org.keycloak.testsuite.pages.LoginPage;
import org.keycloak.testsuite.rule.AbstractKeycloakRule;
import org.keycloak.testsuite.rule.WebResource;
import org.keycloak.testsuite.rule.WebRule;
import org.keycloak.testutils.KeycloakServer;
import org.openqa.selenium.WebDriver;
import java.net.URL;
import java.security.PublicKey;
/**
* Tests Undertow Adapter
*
* @author <a href="mailto:bburke@redhat.com">Bill Burke</a>
*/
public class AdapterTest {
public static PublicKey realmPublicKey;
@ClassRule
public static AbstractKeycloakRule keycloakRule = new AbstractKeycloakRule(){
@Override
protected void configure(RealmManager manager, RealmModel adminRealm) {
RealmRepresentation representation = KeycloakServer.loadJson(getClass().getResourceAsStream("/adapter-test/demorealm.json"), RealmRepresentation.class);
RealmModel realm = manager.importRealm(representation);
realmPublicKey = realm.getPublicKey();
URL url = getClass().getResource("/adapter-test/cust-app-keycloak.json");
deployApplication("customer-portal", "/customer-portal", CustomerServlet.class, url.getPath(), "user");
url = getClass().getResource("/adapter-test/customer-db-keycloak.json");
deployApplication("customer-db", "/customer-db", CustomerDatabaseServlet.class, url.getPath(), "user");
url = getClass().getResource("/adapter-test/product-keycloak.json");
deployApplication("product-portal", "/product-portal", ProductServlet.class, url.getPath(), "user");
}
};
@Rule
public WebRule webRule = new WebRule(this);
@WebResource
protected WebDriver driver;
@WebResource
protected OAuthClient oauth;
@WebResource
protected LoginPage loginPage;
@Test
public void testLogin() throws Exception {
// test login to customer-portal which does a bearer request to customer-db
driver.navigate().to("http://localhost:8081/customer-portal");
System.out.println("Current url: " + driver.getCurrentUrl());
Assert.assertTrue(driver.getCurrentUrl().startsWith("http://localhost:8081/auth"));
loginPage.login("bburke@redhat.com", "password");
System.out.println("Current url: " + driver.getCurrentUrl());
Assert.assertEquals(driver.getCurrentUrl(), "http://localhost:8081/customer-portal");
String pageSource = driver.getPageSource();
System.out.println(pageSource);
Assert.assertTrue(pageSource.contains("Bill Burke") && pageSource.contains("Stian Thorgersen"));
// test SSO
driver.navigate().to("http://localhost:8081/product-portal");
Assert.assertEquals(driver.getCurrentUrl(), "http://localhost:8081/product-portal");
pageSource = driver.getPageSource();
System.out.println(pageSource);
Assert.assertTrue(pageSource.contains("iPhone") && pageSource.contains("iPad"));
}
}

View file

@ -0,0 +1,29 @@
package org.keycloak.testsuite.adapter;
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;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CustomerDatabaseServlet extends HttpServlet {
private static final String LINK = "<a href=\"%s\" id=\"%s\">%s</a>";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.printf("<html><head><title>%s</title></head><body>", "Customer Portal");
pw.println("Stian Thorgersen");
pw.println("Bill Burke");
pw.print("</body></html>");
pw.flush();
}
}

View file

@ -0,0 +1,48 @@
package org.keycloak.testsuite.adapter;
import org.junit.Assert;
import org.keycloak.KeycloakSecurityContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class CustomerServlet extends HttpServlet {
private static final String LINK = "<a href=\"%s\" id=\"%s\">%s</a>";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
KeycloakSecurityContext context = (KeycloakSecurityContext)req.getAttribute(KeycloakSecurityContext.class.getName());
Client client = ClientBuilder.newClient();
try {
WebTarget target = client.target("http://localhost:8081/customer-db");
Response response = target.request().get();
Assert.assertEquals(401, response.getStatus());
response.close();
String html = target.request()
.header(HttpHeaders.AUTHORIZATION, "Bearer " + context.getTokenString())
.get(String.class);
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println(html);
pw.flush();
} finally {
client.close();
}
}
}

View file

@ -0,0 +1,29 @@
package org.keycloak.testsuite.adapter;
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;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public class ProductServlet extends HttpServlet {
private static final String LINK = "<a href=\"%s\" id=\"%s\">%s</a>";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.printf("<html><head><title>%s</title></head><body>", "Product Portal");
pw.println("iPhone");
pw.println("iPad");
pw.print("</body></html>");
pw.flush();
}
}

View file

@ -1,7 +1,10 @@
package org.keycloak.testsuite.rule;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.LoginConfig;
import io.undertow.servlet.api.SecurityConstraint;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.api.WebResourceCollection;
import org.junit.rules.ExternalResource;
import org.keycloak.models.Config;
import org.keycloak.models.Constants;
@ -75,6 +78,11 @@ public abstract class AbstractKeycloakRule extends ExternalResource {
}
public void deployServlet(String name, String contextPath, Class<? extends Servlet> servletClass) {
DeploymentInfo deploymentInfo = createDeploymentInfo(name, contextPath, servletClass);
server.getServer().deploy(deploymentInfo);
}
private DeploymentInfo createDeploymentInfo(String name, String contextPath, Class<? extends Servlet> servletClass) {
DeploymentInfo deploymentInfo = new DeploymentInfo();
deploymentInfo.setClassLoader(getClass().getClassLoader());
deploymentInfo.setDeploymentName(name);
@ -84,7 +92,21 @@ public abstract class AbstractKeycloakRule extends ExternalResource {
servlet.addMapping("/*");
deploymentInfo.addServlet(servlet);
server.getServer().deploy(deploymentInfo);
return deploymentInfo;
}
public void deployApplication(String name, String contextPath, Class<? extends Servlet> servletClass, String adapterConfigPath, String role) {
DeploymentInfo di = createDeploymentInfo(name, contextPath, servletClass);
di.addInitParameter("keycloak.config.file", adapterConfigPath);
SecurityConstraint constraint = new SecurityConstraint();
WebResourceCollection collection = new WebResourceCollection();
collection.addUrlPattern("/*");
constraint.addWebResourceCollection(collection);
constraint.addRoleAllowed(role);
di.addSecurityConstraint(constraint);
LoginConfig loginConfig = new LoginConfig("KEYCLOAK", "demo");
di.setLoginConfig(loginConfig);
server.getServer().deploy(di);
}
@Override

View file

@ -0,0 +1,11 @@
{
"realm": "demo",
"resource": "customer-portal",
"realm-public-key": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"auth-server-url": "http://localhost:8081/auth",
"ssl-not-required": true,
"expose-token": true,
"credentials": {
"secret": "password"
}
}

View file

@ -0,0 +1,8 @@
{
"realm" : "demo",
"resource" : "customer-db",
"realm-public-key" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"bearer-only" : true,
"enable-cors" : true
}

View file

@ -0,0 +1,121 @@
{
"realm": "demo",
"enabled": true,
"accessTokenLifespan": 3000,
"accessCodeLifespan": 10,
"accessCodeLifespanUserAction": 6000,
"sslNotRequired": true,
"registrationAllowed": false,
"social": false,
"updateProfileOnInitialSocialLogin": false,
"privateKey": "MIICXAIBAAKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQABAoGAfmO8gVhyBxdqlxmIuglbz8bcjQbhXJLR2EoS8ngTXmN1bo2L90M0mUKSdc7qF10LgETBzqL8jYlQIbt+e6TH8fcEpKCjUlyq0Mf/vVbfZSNaVycY13nTzo27iPyWQHK5NLuJzn1xvxxrUeXI6A2WFpGEBLbHjwpx5WQG9A+2scECQQDvdn9NE75HPTVPxBqsEd2z10TKkl9CZxu10Qby3iQQmWLEJ9LNmy3acvKrE3gMiYNWb6xHPKiIqOR1as7L24aTAkEAtyvQOlCvr5kAjVqrEKXalj0Tzewjweuxc0pskvArTI2Oo070h65GpoIKLc9jf+UA69cRtquwP93aZKtW06U8dQJAF2Y44ks/mK5+eyDqik3koCI08qaC8HYq2wVl7G2QkJ6sbAaILtcvD92ToOvyGyeE0flvmDZxMYlvaZnaQ0lcSQJBAKZU6umJi3/xeEbkJqMfeLclD27XGEFoPeNrmdx0q10Azp4NfJAY+Z8KRyQCR2BEG+oNitBOZ+YXF9KCpH3cdmECQHEigJhYg+ykOvr1aiZUMFT72HU0jnmQe2FVekuG+LJUt2Tm7GtMjTFoGpf0JwrVuZN39fOYAlo+nTixgeW7X8Y=",
"publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"requiredCredentials": [ "password" ],
"users" : [
{
"username" : "bburke@redhat.com",
"enabled": true,
"email" : "bburke@redhat.com",
"firstName": "Bill",
"lastName": "Burke",
"credentials" : [
{ "type" : "password",
"value" : "password" }
]
}
],
"roles" : {
"realm" : [
{
"name": "user",
"description": "User privileges"
},
{
"name": "admin",
"description": "Administrator privileges"
}
]
},
"roleMappings": [
{
"username": "bburke@redhat.com",
"roles": ["user"]
}
],
"scopeMappings": [
{
"client": "third-party",
"roles": ["user"]
},
{
"client": "customer-portal",
"roles": ["user"]
},
{
"client": "product-portal",
"roles": ["user"]
}
],
"applications": [
{
"name": "customer-portal",
"enabled": true,
"adminUrl": "http://localhost:8081/customer-portal",
"baseUrl": "http://localhost:8081/customer-portal",
"redirectUris": [
"http://localhost:8081/customer-portal/*"
],
"secret": "password"
},
{
"name": "customer-portal-js",
"enabled": true,
"publicClient": true,
"adminUrl": "http://localhost:8081/customer-portal-js",
"baseUrl": "http://localhost:8081/customer-portal-js",
"redirectUris": [
"http://localhost:8080/customer-portal-js/*"
]
},
{
"name": "customer-portal-cli",
"enabled": true,
"publicClient": true,
"redirectUris": [
"urn:ietf:wg:oauth:2.0:oob",
"http://localhost"
]
},
{
"name": "product-portal",
"enabled": true,
"adminUrl": "http://localhost:8081/product-portal",
"baseUrl": "http://localhost:8081/product-portal",
"redirectUris": [
"http://localhost:8081/product-portal/*"
],
"secret": "password"
}
],
"oauthClients": [
{
"name": "third-party",
"enabled": true,
"redirectUris": [
"http://localhost:8081/oauth-client/*",
"http://localhost:8081/oauth-client-cdi/*"
],
"secret": "password"
}
],
"applicationRoleMappings": {
"account": [
{
"username": "bburke@redhat.com",
"roles": ["manage-account"]
}
]
}
}

View file

@ -0,0 +1,10 @@
{
"realm" : "demo",
"resource" : "product-portal",
"realm-public-key" : "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrVrCuTtArbgaZzL1hvh0xtL5mc7o0NqPVnYXkLvgcwiC3BjLGw1tGEGoJaXDuSaRllobm53JBhjx33UNv+5z/UMG4kytBWxheNVKnL6GgqlNabMaFfPLPCF8kAgKnsi79NMo+n6KnSY8YeUmec/p2vjO2NjsSAVcWEQMVhJ31LwIDAQAB",
"auth-server-url" : "http://localhost:8081/auth",
"ssl-not-required" : true,
"credentials" : {
"secret": "password"
}
}