Merge pull request #358 from patriot1burke/master
dynamic key lookup, relative uris
This commit is contained in:
commit
6b470f826e
29 changed files with 862 additions and 183 deletions
|
@ -11,5 +11,6 @@ public interface ServiceUrlConstants {
|
|||
public static final String TOKEN_SERVICE_REFRESH_PATH = "/rest/realms/{realm-name}/tokens/refresh";
|
||||
public static final String TOKEN_SERVICE_LOGOUT_PATH = "/rest/realms/{realm-name}/tokens/logout";
|
||||
public static final String ACCOUNT_SERVICE_PATH = "/rest/realms/{realm-name}/account";
|
||||
public static final String REALM_INFO_PATH = "/rest/realms/{realm-name}";
|
||||
|
||||
}
|
||||
|
|
|
@ -1,12 +1,28 @@
|
|||
package org.keycloak.adapters;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.representations.adapters.config.AdapterConfig;
|
||||
import org.keycloak.representations.idm.PublishedRealmRepresentation;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
import org.keycloak.util.KeycloakUriBuilder;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
|
||||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class AdapterDeploymentContext {
|
||||
private static final Logger log = Logger.getLogger(AdapterDeploymentContext.class);
|
||||
protected KeycloakDeployment deployment;
|
||||
|
||||
public AdapterDeploymentContext() {
|
||||
|
@ -20,6 +36,275 @@ public class AdapterDeploymentContext {
|
|||
return deployment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve adapter deployment based on partial adapter configuration.
|
||||
* This will resolve a relative auth server url based on the current request
|
||||
* This will lazily resolve the public key of the realm if it is not set already.
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public KeycloakDeployment resolveDeployment(HttpFacade facade) {
|
||||
KeycloakDeployment deployment = this.deployment;
|
||||
if (deployment == null) return null;
|
||||
if (deployment.getAuthServerBaseUrl() == null) return deployment;
|
||||
if (deployment.relativeUrls) {
|
||||
deployment = new DeploymentDelegate(this.deployment);
|
||||
deployment.setAuthServerBaseUrl(getBaseBuilder(facade, this.deployment.getAuthServerBaseUrl()).build().toString());
|
||||
}
|
||||
if (deployment.getRealmKey() == null) resolveRealmKey(deployment);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
protected void resolveRealmKey(KeycloakDeployment deployment) {
|
||||
if (deployment.getClient() == null) {
|
||||
throw new RuntimeException("KeycloakDeployment was never initialized through appropriate SPIs");
|
||||
}
|
||||
HttpGet get = new HttpGet(deployment.getRealmInfoUrl());
|
||||
try {
|
||||
HttpResponse response = deployment.getClient().execute(get);
|
||||
int status = response.getStatusLine().getStatusCode();
|
||||
if (status != 200) {
|
||||
close(response);
|
||||
throw new RuntimeException("Unable to resolve realm public key remotely, status = " + status);
|
||||
}
|
||||
HttpEntity entity = response.getEntity();
|
||||
if (entity == null) {
|
||||
throw new RuntimeException("Unable to resolve realm public key remotely. There was no entity.");
|
||||
}
|
||||
InputStream is = entity.getContent();
|
||||
try {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream();
|
||||
int c;
|
||||
while ((c = is.read()) != -1) {
|
||||
os.write(c);
|
||||
}
|
||||
byte[] bytes = os.toByteArray();
|
||||
String json = new String(bytes);
|
||||
PublishedRealmRepresentation rep = JsonSerialization.readValue(json, PublishedRealmRepresentation.class);
|
||||
deployment.setRealmKey(rep.getPublicKey());
|
||||
} finally {
|
||||
try {
|
||||
is.close();
|
||||
} catch (IOException ignored) {
|
||||
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Unable to resolve realm public key remotely", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This delegate is used to store temporary, per-request metadata like request resolved URLs.
|
||||
* Ever method is delegated except URL get methods and isConfigured()
|
||||
*
|
||||
*/
|
||||
protected static class DeploymentDelegate extends KeycloakDeployment {
|
||||
protected KeycloakDeployment delegate;
|
||||
|
||||
public DeploymentDelegate(KeycloakDeployment delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getResourceName() {
|
||||
return delegate.getResourceName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRealm() {
|
||||
return delegate.getRealm();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRealm(String realm) {
|
||||
delegate.setRealm(realm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PublicKey getRealmKey() {
|
||||
return delegate.getRealmKey();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRealmKey(PublicKey realmKey) {
|
||||
delegate.setRealmKey(realmKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setResourceName(String resourceName) {
|
||||
delegate.setResourceName(resourceName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBearerOnly() {
|
||||
return delegate.isBearerOnly();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBearerOnly(boolean bearerOnly) {
|
||||
delegate.setBearerOnly(bearerOnly);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isPublicClient() {
|
||||
return delegate.isPublicClient();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPublicClient(boolean publicClient) {
|
||||
delegate.setPublicClient(publicClient);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getResourceCredentials() {
|
||||
return delegate.getResourceCredentials();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setResourceCredentials(Map<String, String> resourceCredentials) {
|
||||
delegate.setResourceCredentials(resourceCredentials);
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClient getClient() {
|
||||
return delegate.getClient();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setClient(HttpClient client) {
|
||||
delegate.setClient(client);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getScope() {
|
||||
return delegate.getScope();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setScope(String scope) {
|
||||
delegate.setScope(scope);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSslRequired() {
|
||||
return delegate.isSslRequired();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSslRequired(boolean sslRequired) {
|
||||
delegate.setSslRequired(sslRequired);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getStateCookieName() {
|
||||
return delegate.getStateCookieName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStateCookieName(String stateCookieName) {
|
||||
delegate.setStateCookieName(stateCookieName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUseResourceRoleMappings() {
|
||||
return delegate.isUseResourceRoleMappings();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setUseResourceRoleMappings(boolean useResourceRoleMappings) {
|
||||
delegate.setUseResourceRoleMappings(useResourceRoleMappings);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCors() {
|
||||
return delegate.isCors();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCors(boolean cors) {
|
||||
delegate.setCors(cors);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getCorsMaxAge() {
|
||||
return delegate.getCorsMaxAge();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCorsMaxAge(int corsMaxAge) {
|
||||
delegate.setCorsMaxAge(corsMaxAge);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCorsAllowedHeaders() {
|
||||
return delegate.getCorsAllowedHeaders();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setNotBefore(int notBefore) {
|
||||
delegate.setNotBefore(notBefore);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getNotBefore() {
|
||||
return delegate.getNotBefore();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExposeToken(boolean exposeToken) {
|
||||
delegate.setExposeToken(exposeToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isExposeToken() {
|
||||
return delegate.isExposeToken();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCorsAllowedMethods(String corsAllowedMethods) {
|
||||
delegate.setCorsAllowedMethods(corsAllowedMethods);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getCorsAllowedMethods() {
|
||||
return delegate.getCorsAllowedMethods();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setCorsAllowedHeaders(String corsAllowedHeaders) {
|
||||
delegate.setCorsAllowedHeaders(corsAllowedHeaders);
|
||||
}
|
||||
}
|
||||
|
||||
protected KeycloakUriBuilder getBaseBuilder(HttpFacade facade, String base) {
|
||||
KeycloakUriBuilder builder = KeycloakUriBuilder.fromUri(base);
|
||||
URI request = URI.create(facade.getRequest().getURI());
|
||||
String scheme = "http";
|
||||
if (deployment.isSslRequired()) {
|
||||
scheme = "https";
|
||||
}
|
||||
if (!request.getScheme().equals(scheme) && request.getPort() != -1) {
|
||||
throw new RuntimeException("Can't resolve relative url from adapter config.");
|
||||
}
|
||||
builder.scheme(scheme);
|
||||
builder.host(request.getHost());
|
||||
builder.port(request.getPort());
|
||||
return builder;
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected void close(HttpResponse response) {
|
||||
if (response.getEntity() != null) {
|
||||
try {
|
||||
response.getEntity().getContent().close();
|
||||
} catch (IOException e) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateDeployment(AdapterConfig config) {
|
||||
deployment = KeycloakDeploymentBuilder.build(config);
|
||||
}
|
||||
|
|
|
@ -1,8 +1,12 @@
|
|||
package org.keycloak.adapters;
|
||||
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.OAuth2Constants;
|
||||
import org.keycloak.ServiceUrlConstants;
|
||||
import org.keycloak.util.KeycloakUriBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.security.PublicKey;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
@ -12,9 +16,14 @@ import java.util.Map;
|
|||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class KeycloakDeployment {
|
||||
protected boolean configured;
|
||||
private static final Logger log = Logger.getLogger(KeycloakDeployment.class);
|
||||
|
||||
protected boolean relativeUrls;
|
||||
protected String realm;
|
||||
protected PublicKey realmKey;
|
||||
protected KeycloakUriBuilder serverBuilder;
|
||||
protected String authServerBaseUrl;
|
||||
protected String realmInfoUrl;
|
||||
protected KeycloakUriBuilder authUrl;
|
||||
protected String codeUrl;
|
||||
protected String refreshUrl;
|
||||
|
@ -38,12 +47,11 @@ public class KeycloakDeployment {
|
|||
protected boolean exposeToken;
|
||||
protected volatile int notBefore;
|
||||
|
||||
public boolean isConfigured() {
|
||||
return configured;
|
||||
public KeycloakDeployment() {
|
||||
}
|
||||
|
||||
public void setConfigured(boolean configured) {
|
||||
this.configured = configured;
|
||||
public boolean isConfigured() {
|
||||
return getRealm() != null && getRealmKey() != null && (isBearerOnly() || getAuthServerBaseUrl() != null);
|
||||
}
|
||||
|
||||
public String getResourceName() {
|
||||
|
@ -66,28 +74,54 @@ public class KeycloakDeployment {
|
|||
this.realmKey = realmKey;
|
||||
}
|
||||
|
||||
public KeycloakUriBuilder getAuthUrl() {
|
||||
return authUrl;
|
||||
public String getAuthServerBaseUrl() {
|
||||
return authServerBaseUrl;
|
||||
}
|
||||
|
||||
public void setAuthUrl(KeycloakUriBuilder authUrl) {
|
||||
this.authUrl = authUrl;
|
||||
public void setAuthServerBaseUrl(String authServerBaseUrl) {
|
||||
this.authServerBaseUrl = authServerBaseUrl;
|
||||
if (authServerBaseUrl == null) return;
|
||||
|
||||
URI uri = URI.create(authServerBaseUrl);
|
||||
if (uri.getHost() == null) {
|
||||
relativeUrls = true;
|
||||
return;
|
||||
}
|
||||
|
||||
relativeUrls = false;
|
||||
|
||||
serverBuilder = KeycloakUriBuilder.fromUri(authServerBaseUrl);
|
||||
String login = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGIN_PATH).build(getRealm()).toString();
|
||||
authUrl = KeycloakUriBuilder.fromUri(login);
|
||||
refreshUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_REFRESH_PATH).build(getRealm()).toString();
|
||||
logoutUrl = KeycloakUriBuilder.fromUri(serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH).build(getRealm()).toString());
|
||||
accountUrl = serverBuilder.clone().path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH).build(getRealm()).toString();
|
||||
realmInfoUrl = serverBuilder.clone().path(ServiceUrlConstants.REALM_INFO_PATH).build(getRealm()).toString();
|
||||
codeUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_ACCESS_CODE_PATH).build(getRealm()).toString();
|
||||
}
|
||||
|
||||
public String getRealmInfoUrl() {
|
||||
return realmInfoUrl;
|
||||
}
|
||||
|
||||
public KeycloakUriBuilder getAuthUrl() {
|
||||
return authUrl;
|
||||
}
|
||||
|
||||
public String getCodeUrl() {
|
||||
return codeUrl;
|
||||
}
|
||||
|
||||
public void setCodeUrl(String codeUrl) {
|
||||
this.codeUrl = codeUrl;
|
||||
}
|
||||
|
||||
public String getRefreshUrl() {
|
||||
return refreshUrl;
|
||||
}
|
||||
|
||||
public void setRefreshUrl(String refreshUrl) {
|
||||
this.refreshUrl = refreshUrl;
|
||||
public KeycloakUriBuilder getLogoutUrl() {
|
||||
return logoutUrl;
|
||||
}
|
||||
|
||||
public String getAccountUrl() {
|
||||
return accountUrl;
|
||||
}
|
||||
|
||||
public void setResourceName(String resourceName) {
|
||||
|
@ -206,19 +240,4 @@ public class KeycloakDeployment {
|
|||
this.notBefore = notBefore;
|
||||
}
|
||||
|
||||
public KeycloakUriBuilder getLogoutUrl() {
|
||||
return logoutUrl;
|
||||
}
|
||||
|
||||
public void setLogoutUrl(KeycloakUriBuilder logoutUrl) {
|
||||
this.logoutUrl = logoutUrl;
|
||||
}
|
||||
|
||||
public String getAccountUrl() {
|
||||
return accountUrl;
|
||||
}
|
||||
|
||||
public void setAccountUrl(String accountUrl) {
|
||||
this.accountUrl = accountUrl;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,14 +5,11 @@ import org.codehaus.jackson.map.annotate.JsonSerialize;
|
|||
import org.keycloak.OAuth2Constants;
|
||||
import org.keycloak.ServiceUrlConstants;
|
||||
import org.keycloak.representations.adapters.config.AdapterConfig;
|
||||
import org.keycloak.util.EnvUtil;
|
||||
import org.keycloak.util.KeycloakUriBuilder;
|
||||
import org.keycloak.util.KeystoreUtil;
|
||||
import org.keycloak.util.PemUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.KeyStore;
|
||||
import java.security.PublicKey;
|
||||
|
||||
/**
|
||||
|
@ -22,12 +19,11 @@ import java.security.PublicKey;
|
|||
public class KeycloakDeploymentBuilder {
|
||||
protected KeycloakDeployment deployment = new KeycloakDeployment();
|
||||
|
||||
protected KeycloakDeploymentBuilder() {}
|
||||
|
||||
protected KeycloakDeploymentBuilder() {
|
||||
}
|
||||
|
||||
|
||||
protected KeycloakDeployment internalBuild(AdapterConfig adapterConfig) {
|
||||
deployment.setConfigured(true);
|
||||
if (adapterConfig.getRealm() == null) throw new RuntimeException("Must set 'realm' in config");
|
||||
deployment.setRealm(adapterConfig.getRealm());
|
||||
String resource = adapterConfig.getResource();
|
||||
|
@ -35,17 +31,15 @@ public class KeycloakDeploymentBuilder {
|
|||
deployment.setResourceName(resource);
|
||||
|
||||
String realmKeyPem = adapterConfig.getRealmKey();
|
||||
if (realmKeyPem == null) {
|
||||
throw new IllegalArgumentException("You must set the realm-public-key");
|
||||
if (realmKeyPem != null) {
|
||||
PublicKey realmKey = null;
|
||||
try {
|
||||
realmKey = PemUtils.decodePublicKey(realmKeyPem);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
deployment.setRealmKey(realmKey);
|
||||
}
|
||||
|
||||
PublicKey realmKey = null;
|
||||
try {
|
||||
realmKey = PemUtils.decodePublicKey(realmKeyPem);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
deployment.setRealmKey(realmKey);
|
||||
deployment.setSslRequired(!adapterConfig.isSslNotRequired());
|
||||
deployment.setResourceCredentials(adapterConfig.getCredentials());
|
||||
deployment.setPublicClient(adapterConfig.isPublicClient());
|
||||
|
@ -58,28 +52,21 @@ public class KeycloakDeploymentBuilder {
|
|||
deployment.setCorsAllowedMethods(adapterConfig.getCorsAllowedMethods());
|
||||
}
|
||||
|
||||
deployment.setBearerOnly(adapterConfig.isBearerOnly());
|
||||
|
||||
if (adapterConfig.isBearerOnly()) {
|
||||
deployment.setBearerOnly(true);
|
||||
return deployment;
|
||||
}
|
||||
|
||||
deployment.setClient(new HttpClientBuilder().build(adapterConfig));
|
||||
if (adapterConfig.getAuthServerUrl() == null) {
|
||||
if (realmKeyPem == null && adapterConfig.isBearerOnly() && adapterConfig.getAuthServerUrl() == null) {
|
||||
throw new IllegalArgumentException("For bearer auth, you must set the realm-public-key or auth-server-url");
|
||||
}
|
||||
if (realmKeyPem == null || !deployment.isBearerOnly()) {
|
||||
deployment.setClient(new HttpClientBuilder().build(adapterConfig));
|
||||
}
|
||||
if (adapterConfig.getAuthServerUrl() == null && (!deployment.isBearerOnly() || realmKeyPem == null)) {
|
||||
throw new RuntimeException("You must specify auth-url");
|
||||
}
|
||||
KeycloakUriBuilder serverBuilder = KeycloakUriBuilder.fromUri(adapterConfig.getAuthServerUrl());
|
||||
String authUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGIN_PATH).build(adapterConfig.getRealm()).toString();
|
||||
String tokenUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_ACCESS_CODE_PATH).build(adapterConfig.getRealm()).toString();
|
||||
String refreshUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_REFRESH_PATH).build(adapterConfig.getRealm()).toString();
|
||||
String logoutUrl = serverBuilder.clone().path(ServiceUrlConstants.TOKEN_SERVICE_LOGOUT_PATH).build(adapterConfig.getRealm()).toString();
|
||||
String accountUrl = serverBuilder.clone().path(ServiceUrlConstants.ACCOUNT_SERVICE_PATH).build(adapterConfig.getRealm()).toString();
|
||||
|
||||
deployment.setAuthUrl(KeycloakUriBuilder.fromUri(authUrl).queryParam(OAuth2Constants.CLIENT_ID, deployment.getResourceName()));
|
||||
deployment.setCodeUrl(tokenUrl);
|
||||
deployment.setRefreshUrl(refreshUrl);
|
||||
deployment.setLogoutUrl(KeycloakUriBuilder.fromUri(logoutUrl));
|
||||
deployment.setAccountUrl(accountUrl);
|
||||
|
||||
deployment.setAuthServerBaseUrl(adapterConfig.getAuthServerUrl());
|
||||
return deployment;
|
||||
}
|
||||
|
||||
|
|
|
@ -25,32 +25,46 @@ public class PreAuthActionsHandler {
|
|||
private static final Logger log = Logger.getLogger(PreAuthActionsHandler.class);
|
||||
|
||||
protected UserSessionManagement userSessionManagement;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
protected KeycloakDeployment deployment;
|
||||
protected HttpFacade facade;
|
||||
|
||||
public PreAuthActionsHandler(UserSessionManagement userSessionManagement, KeycloakDeployment deployment, HttpFacade facade) {
|
||||
public PreAuthActionsHandler(UserSessionManagement userSessionManagement, AdapterDeploymentContext deploymentContext, HttpFacade facade) {
|
||||
this.userSessionManagement = userSessionManagement;
|
||||
this.deployment = deployment;
|
||||
this.deploymentContext = deploymentContext;
|
||||
this.facade = facade;
|
||||
}
|
||||
|
||||
protected boolean resolveDeployment() {
|
||||
deployment = deploymentContext.resolveDeployment(facade);
|
||||
if (!deployment.isConfigured()) {
|
||||
log.warn("can't take request, adapter not configured");
|
||||
facade.getResponse().sendError(403, "adapter not configured");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean handleRequest() {
|
||||
if (!deployment.isConfigured()) return false;
|
||||
String requestUri = facade.getRequest().getURI();
|
||||
log.debugv("adminRequest {0}", requestUri);
|
||||
if (preflightCors()) {
|
||||
return true;
|
||||
}
|
||||
if (requestUri.endsWith(AdapterConstants.K_LOGOUT)) {
|
||||
if (!resolveDeployment()) return true;
|
||||
handleLogout();
|
||||
return true;
|
||||
} else if (requestUri.endsWith(AdapterConstants.K_PUSH_NOT_BEFORE)) {
|
||||
if (!resolveDeployment()) return true;
|
||||
handlePushNotBefore();
|
||||
return true;
|
||||
} else if (requestUri.endsWith(AdapterConstants.K_GET_SESSION_STATS)) {
|
||||
if (!resolveDeployment()) return true;
|
||||
handleGetSessionStats();
|
||||
return true;
|
||||
}else if (requestUri.endsWith(AdapterConstants.K_GET_USER_STATS)) {
|
||||
if (!resolveDeployment()) return true;
|
||||
handleGetUserStats();
|
||||
return true;
|
||||
}
|
||||
|
@ -58,6 +72,9 @@ public class PreAuthActionsHandler {
|
|||
}
|
||||
|
||||
public boolean preflightCors() {
|
||||
// don't need to resolve deployment on cors requests. Just need to know local cors config.
|
||||
KeycloakDeployment deployment = deploymentContext.getDeployment();
|
||||
if (!deployment.isCors()) return false;
|
||||
log.debugv("checkCorsPreflight {0}", facade.getRequest().getURI());
|
||||
if (!facade.getRequest().getMethod().equalsIgnoreCase("OPTIONS")) {
|
||||
return false;
|
||||
|
@ -134,6 +151,11 @@ public class PreAuthActionsHandler {
|
|||
}
|
||||
|
||||
protected JWSInput verifyAdminRequest() throws Exception {
|
||||
if (deployment.isSslRequired() && !facade.getRequest().isSecure()) {
|
||||
log.warn("SSL is required for adapter admin action");
|
||||
facade.getResponse().sendError(403, "ssl required");
|
||||
|
||||
}
|
||||
String token = StreamUtil.readString(facade.getRequest().getInputStream());
|
||||
if (token == null) {
|
||||
log.warn("admin request failed, no token");
|
||||
|
|
|
@ -169,8 +169,7 @@ public class ServerRequest {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
protected static void error(int status, HttpEntity entity) throws HttpFailure, IOException {
|
||||
public static void error(int status, HttpEntity entity) throws HttpFailure, IOException {
|
||||
String body = null;
|
||||
if (entity != null) {
|
||||
InputStream is = entity.getContent();
|
||||
|
|
|
@ -48,9 +48,14 @@ public class AuthenticatedActionsValve extends ValveBase {
|
|||
@Override
|
||||
public void invoke(Request request, Response response) throws IOException, ServletException {
|
||||
log.debugv("AuthenticatedActionsValve.invoke {0}", request.getRequestURI());
|
||||
AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deploymentContext.getDeployment(), new CatalinaHttpFacade(request, response));
|
||||
if (handler.handledRequest()) {
|
||||
return;
|
||||
CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response);
|
||||
KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
|
||||
if (deployment != null && deployment.isConfigured()) {
|
||||
AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, new CatalinaHttpFacade(request, response));
|
||||
if (handler.handledRequest()) {
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
getNext().invoke(request, response);
|
||||
}
|
||||
|
|
|
@ -16,33 +16,20 @@ import org.keycloak.adapters.AdapterConstants;
|
|||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.AuthChallenge;
|
||||
import org.keycloak.adapters.AuthOutcome;
|
||||
import org.keycloak.adapters.HttpFacade;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
import org.keycloak.adapters.KeycloakDeploymentBuilder;
|
||||
import org.keycloak.adapters.PreAuthActionsHandler;
|
||||
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
|
||||
import org.keycloak.representations.adapters.action.AdminAction;
|
||||
import org.keycloak.representations.adapters.action.PushNotBeforeAction;
|
||||
import org.keycloak.representations.adapters.action.SessionStats;
|
||||
import org.keycloak.representations.adapters.action.SessionStatsAction;
|
||||
import org.keycloak.representations.adapters.action.UserStats;
|
||||
import org.keycloak.representations.adapters.action.UserStatsAction;
|
||||
import org.keycloak.jose.jws.JWSInput;
|
||||
import org.keycloak.jose.jws.crypto.RSAProvider;
|
||||
import org.keycloak.representations.adapters.action.LogoutAction;
|
||||
import org.keycloak.util.JsonSerialization;
|
||||
import org.keycloak.util.StreamUtil;
|
||||
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Web deployment whose security is managed by a remote OAuth Skeleton Key authentication server
|
||||
|
@ -81,6 +68,7 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
|||
log.info(json);
|
||||
return new ByteArrayInputStream(json.getBytes());
|
||||
}
|
||||
|
||||
private static InputStream getConfigInputStream(Context context) {
|
||||
InputStream is = getJSONFromServletContext(context.getServletContext());
|
||||
if (is == null) {
|
||||
|
@ -106,8 +94,6 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
|||
if (configInputStream == null) {
|
||||
log.warn("No adapter configuration. Keycloak is unconfigured and will deny all requests.");
|
||||
kd = new KeycloakDeployment();
|
||||
kd.setConfigured(false);
|
||||
|
||||
} else {
|
||||
kd = KeycloakDeploymentBuilder.build(configInputStream);
|
||||
}
|
||||
|
@ -120,11 +106,12 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
|||
@Override
|
||||
public void invoke(Request request, Response response) throws IOException, ServletException {
|
||||
try {
|
||||
PreAuthActionsHandler handler = new PreAuthActionsHandler(userSessionManagement, deploymentContext.getDeployment(), new CatalinaHttpFacade(request, response));
|
||||
CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response);
|
||||
PreAuthActionsHandler handler = new PreAuthActionsHandler(userSessionManagement, deploymentContext, facade);
|
||||
if (handler.handleRequest()) {
|
||||
return;
|
||||
}
|
||||
checkKeycloakSession(request);
|
||||
checkKeycloakSession(request, facade);
|
||||
super.invoke(request, response);
|
||||
} finally {
|
||||
}
|
||||
|
@ -132,9 +119,13 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
|||
|
||||
@Override
|
||||
public boolean authenticate(Request request, HttpServletResponse response, LoginConfig config) throws IOException {
|
||||
if (!deploymentContext.getDeployment().isConfigured()) return false;
|
||||
CatalinaHttpFacade facade = new CatalinaHttpFacade(request, response);
|
||||
CatalinaRequestAuthenticator authenticator = new CatalinaRequestAuthenticator(deploymentContext.getDeployment(), this, userSessionManagement, facade, request);
|
||||
KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
|
||||
if (deployment == null || !deployment.isConfigured()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
CatalinaRequestAuthenticator authenticator = new CatalinaRequestAuthenticator(deployment, this, userSessionManagement, facade, request);
|
||||
AuthOutcome outcome = authenticator.authenticate();
|
||||
if (outcome == AuthOutcome.AUTHENTICATED) {
|
||||
if (facade.isEnded()) {
|
||||
|
@ -147,19 +138,19 @@ public class KeycloakAuthenticatorValve extends FormAuthenticator implements Lif
|
|||
challenge.challenge(facade);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that access token is still valid. Will attempt refresh of token if it is not.
|
||||
*
|
||||
* @param request
|
||||
*/
|
||||
protected void checkKeycloakSession(Request request) {
|
||||
protected void checkKeycloakSession(Request request, HttpFacade facade) {
|
||||
if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return;
|
||||
RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext)request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName());
|
||||
RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName());
|
||||
if (session == null) return;
|
||||
// just in case session got serialized
|
||||
session.setDeployment(deploymentContext.getDeployment());
|
||||
if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade));
|
||||
if (session.isActive()) return;
|
||||
|
||||
// FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will
|
||||
|
|
|
@ -14,6 +14,7 @@ import io.undertow.servlet.api.ServletSessionConfig;
|
|||
import java.io.ByteArrayInputStream;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.adapters.AdapterConstants;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.AuthenticatedActionsHandler;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
import org.keycloak.adapters.KeycloakDeploymentBuilder;
|
||||
|
@ -80,16 +81,22 @@ public class KeycloakServletExtension implements ServletExtension {
|
|||
}
|
||||
log.info("KeycloakServletException initialization");
|
||||
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);
|
||||
final ServletKeycloakAuthMech mech = createAuthenticationMechanism(deploymentInfo, deployment, userSessionManagement);
|
||||
KeycloakDeployment deployment = null;
|
||||
if (is == null) {
|
||||
throw new RuntimeException("Unable to find realm config in /WEB-INF/keycloak.json or in keycloak subsystem.");
|
||||
} else {
|
||||
deployment = KeycloakDeploymentBuilder.build(is);
|
||||
|
||||
UndertowAuthenticatedActionsHandler.Wrapper actions = new UndertowAuthenticatedActionsHandler.Wrapper(deployment);
|
||||
}
|
||||
AdapterDeploymentContext deploymentContext = new AdapterDeploymentContext(deployment);
|
||||
UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement();
|
||||
final ServletKeycloakAuthMech mech = createAuthenticationMechanism(deploymentInfo, deploymentContext, userSessionManagement);
|
||||
|
||||
UndertowAuthenticatedActionsHandler.Wrapper actions = new UndertowAuthenticatedActionsHandler.Wrapper(deploymentContext);
|
||||
|
||||
// setup handlers
|
||||
|
||||
deploymentInfo.addOuterHandlerChainWrapper(new ServletPreAuthActionsHandler.Wrapper(deployment, userSessionManagement));
|
||||
deploymentInfo.addOuterHandlerChainWrapper(new ServletPreAuthActionsHandler.Wrapper(deploymentContext, userSessionManagement));
|
||||
deploymentInfo.addAuthenticationMechanism("KEYCLOAK", new AuthenticationMechanismFactory() {
|
||||
@Override
|
||||
public AuthenticationMechanism create(String s, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
|
||||
|
@ -121,8 +128,8 @@ public class KeycloakServletExtension implements ServletExtension {
|
|||
deploymentInfo.setServletSessionConfig(cookieConfig);
|
||||
}
|
||||
|
||||
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, KeycloakDeployment deployment, UndertowUserSessionManagement userSessionManagement) {
|
||||
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) {
|
||||
log.info("creating ServletKeycloakAuthMech");
|
||||
return new ServletKeycloakAuthMech(deployment, userSessionManagement, deploymentInfo.getConfidentialPortManager());
|
||||
return new ServletKeycloakAuthMech(deploymentContext, userSessionManagement, deploymentInfo.getConfidentialPortManager());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,6 +5,7 @@ import io.undertow.security.api.SecurityContext;
|
|||
import io.undertow.server.HttpServerExchange;
|
||||
import io.undertow.servlet.api.ConfidentialPortManager;
|
||||
import io.undertow.util.AttachmentKey;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.AuthChallenge;
|
||||
import org.keycloak.adapters.AuthOutcome;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
|
@ -16,12 +17,12 @@ import org.keycloak.adapters.KeycloakDeployment;
|
|||
public class ServletKeycloakAuthMech implements AuthenticationMechanism {
|
||||
public static final AttachmentKey<AuthChallenge> KEYCLOAK_CHALLENGE_ATTACHMENT_KEY = AttachmentKey.create(AuthChallenge.class);
|
||||
|
||||
protected KeycloakDeployment deployment;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
protected UndertowUserSessionManagement userSessionManagement;
|
||||
protected ConfidentialPortManager portManager;
|
||||
|
||||
public ServletKeycloakAuthMech(KeycloakDeployment deployment, UndertowUserSessionManagement userSessionManagement, ConfidentialPortManager portManager) {
|
||||
this.deployment = deployment;
|
||||
public ServletKeycloakAuthMech(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement, ConfidentialPortManager portManager) {
|
||||
this.deploymentContext = deploymentContext;
|
||||
this.userSessionManagement = userSessionManagement;
|
||||
this.portManager = portManager;
|
||||
}
|
||||
|
@ -29,7 +30,11 @@ public class ServletKeycloakAuthMech implements AuthenticationMechanism {
|
|||
@Override
|
||||
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
|
||||
UndertowHttpFacade facade = new UndertowHttpFacade(exchange);
|
||||
ServletRequestAuthenticator authenticator = createRequestAuthenticator(exchange, securityContext, facade);
|
||||
KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
|
||||
if (!deployment.isConfigured()) {
|
||||
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
|
||||
}
|
||||
ServletRequestAuthenticator authenticator = createRequestAuthenticator(deployment, exchange, securityContext, facade);
|
||||
AuthOutcome outcome = authenticator.authenticate();
|
||||
if (outcome == AuthOutcome.AUTHENTICATED) {
|
||||
return AuthenticationMechanismOutcome.AUTHENTICATED;
|
||||
|
@ -45,7 +50,7 @@ public class ServletKeycloakAuthMech implements AuthenticationMechanism {
|
|||
return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
|
||||
}
|
||||
|
||||
protected ServletRequestAuthenticator createRequestAuthenticator(HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
|
||||
protected ServletRequestAuthenticator createRequestAuthenticator(KeycloakDeployment deployment, HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
|
||||
int confidentialPort = 8443;
|
||||
if (portManager != null) confidentialPort = portManager.getConfidentialPort(exchange);
|
||||
return new ServletRequestAuthenticator(facade, deployment,
|
||||
|
|
|
@ -5,6 +5,7 @@ import io.undertow.server.HttpHandler;
|
|||
import io.undertow.server.HttpServerExchange;
|
||||
import io.undertow.servlet.handlers.ServletRequestContext;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.PreAuthActionsHandler;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
|
||||
|
@ -17,37 +18,38 @@ public class ServletPreAuthActionsHandler implements HttpHandler {
|
|||
private static final Logger log = Logger.getLogger(ServletPreAuthActionsHandler.class);
|
||||
protected HttpHandler next;
|
||||
protected UndertowUserSessionManagement userSessionManagement;
|
||||
protected KeycloakDeployment deployment;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
|
||||
public static class Wrapper implements HandlerWrapper {
|
||||
protected KeycloakDeployment deployment;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
protected UndertowUserSessionManagement userSessionManagement;
|
||||
|
||||
|
||||
public Wrapper(KeycloakDeployment deployment, UndertowUserSessionManagement userSessionManagement) {
|
||||
this.deployment = deployment;
|
||||
public Wrapper(AdapterDeploymentContext deploymentContext, UndertowUserSessionManagement userSessionManagement) {
|
||||
this.deploymentContext = deploymentContext;
|
||||
this.userSessionManagement = userSessionManagement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHandler wrap(HttpHandler handler) {
|
||||
return new ServletPreAuthActionsHandler(deployment, userSessionManagement, handler);
|
||||
return new ServletPreAuthActionsHandler(deploymentContext, userSessionManagement, handler);
|
||||
}
|
||||
}
|
||||
|
||||
protected ServletPreAuthActionsHandler(KeycloakDeployment deployment,
|
||||
protected ServletPreAuthActionsHandler(AdapterDeploymentContext deploymentContext,
|
||||
UndertowUserSessionManagement userSessionManagement,
|
||||
HttpHandler next) {
|
||||
this.next = next;
|
||||
this.deployment = deployment;
|
||||
this.deploymentContext = deploymentContext;
|
||||
this.userSessionManagement = userSessionManagement;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequest(HttpServerExchange exchange) throws Exception {
|
||||
UndertowHttpFacade facade = new UndertowHttpFacade(exchange);
|
||||
final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
|
||||
SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, servletRequestContext.getDeployment().getSessionManager());
|
||||
PreAuthActionsHandler handler = new PreAuthActionsHandler(bridge, deployment, new UndertowHttpFacade(exchange));
|
||||
PreAuthActionsHandler handler = new PreAuthActionsHandler(bridge, deploymentContext, facade);
|
||||
if (handler.handleRequest()) return;
|
||||
next.handleRequest(exchange);
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@ import io.undertow.server.HandlerWrapper;
|
|||
import io.undertow.server.HttpHandler;
|
||||
import io.undertow.server.HttpServerExchange;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.AuthenticatedActionsHandler;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
|
||||
|
@ -15,32 +16,36 @@ import org.keycloak.adapters.KeycloakDeployment;
|
|||
*/
|
||||
public class UndertowAuthenticatedActionsHandler implements HttpHandler {
|
||||
private static final Logger log = Logger.getLogger(UndertowAuthenticatedActionsHandler.class);
|
||||
protected KeycloakDeployment deployment;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
protected HttpHandler next;
|
||||
|
||||
public static class Wrapper implements HandlerWrapper {
|
||||
protected KeycloakDeployment deployment;
|
||||
protected AdapterDeploymentContext deploymentContext;
|
||||
|
||||
public Wrapper(KeycloakDeployment deployment) {
|
||||
this.deployment = deployment;
|
||||
public Wrapper(AdapterDeploymentContext deploymentContext) {
|
||||
this.deploymentContext = deploymentContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpHandler wrap(HttpHandler handler) {
|
||||
return new UndertowAuthenticatedActionsHandler(deployment, handler);
|
||||
return new UndertowAuthenticatedActionsHandler(deploymentContext, handler);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected UndertowAuthenticatedActionsHandler(KeycloakDeployment deployment, HttpHandler next) {
|
||||
this.deployment = deployment;
|
||||
protected UndertowAuthenticatedActionsHandler(AdapterDeploymentContext deploymentContext, HttpHandler next) {
|
||||
this.deploymentContext = deploymentContext;
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequest(HttpServerExchange exchange) throws Exception {
|
||||
AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, new UndertowHttpFacade(exchange));
|
||||
if (handler.handledRequest()) return;
|
||||
UndertowHttpFacade facade = new UndertowHttpFacade(exchange);
|
||||
KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
|
||||
if (deployment != null && deployment.isConfigured()) {
|
||||
AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, facade);
|
||||
if (handler.handledRequest()) return;
|
||||
}
|
||||
next.handleRequest(exchange);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,11 +33,6 @@ public class UndertowUserSessionManagement implements SessionListener {
|
|||
private static final String AUTH_SESSION_NAME = CachedAuthenticatedSessionHandler.class.getName() + ".AuthenticatedSession";
|
||||
protected ConcurrentHashMap<String, UserSessions> userSessionMap = new ConcurrentHashMap<String, UserSessions>();
|
||||
|
||||
protected KeycloakDeployment deployment;
|
||||
|
||||
public UndertowUserSessionManagement(KeycloakDeployment deployment) {
|
||||
this.deployment = deployment;
|
||||
}
|
||||
|
||||
public static class UserSessions {
|
||||
protected Set<String> sessionIds = new HashSet<String>();
|
||||
|
|
|
@ -3,6 +3,7 @@ package org.keycloak.adapters.wildfly;
|
|||
import io.undertow.security.api.SecurityContext;
|
||||
import io.undertow.server.HttpServerExchange;
|
||||
import io.undertow.servlet.api.ConfidentialPortManager;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
import org.keycloak.adapters.undertow.ServletKeycloakAuthMech;
|
||||
import org.keycloak.adapters.undertow.ServletRequestAuthenticator;
|
||||
|
@ -15,14 +16,14 @@ import org.keycloak.adapters.undertow.UndertowUserSessionManagement;
|
|||
*/
|
||||
public class WildflyAuthenticationMechanism extends ServletKeycloakAuthMech {
|
||||
|
||||
public WildflyAuthenticationMechanism(KeycloakDeployment deployment,
|
||||
public WildflyAuthenticationMechanism(AdapterDeploymentContext deploymentContext,
|
||||
UndertowUserSessionManagement userSessionManagement,
|
||||
ConfidentialPortManager portManager) {
|
||||
super(deployment, userSessionManagement, portManager);
|
||||
super(deploymentContext, userSessionManagement, portManager);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ServletRequestAuthenticator createRequestAuthenticator(HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
|
||||
protected ServletRequestAuthenticator createRequestAuthenticator(KeycloakDeployment deployment, HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
|
||||
return new WildflyRequestAuthenticator(facade, deployment,
|
||||
portManager.getConfidentialPort(exchange), securityContext, exchange, userSessionManagement);
|
||||
}
|
||||
|
|
|
@ -2,6 +2,7 @@ package org.keycloak.adapters.wildfly;
|
|||
|
||||
import io.undertow.servlet.api.DeploymentInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.keycloak.adapters.AdapterDeploymentContext;
|
||||
import org.keycloak.adapters.KeycloakDeployment;
|
||||
import org.keycloak.adapters.undertow.KeycloakServletExtension;
|
||||
import org.keycloak.adapters.undertow.ServletKeycloakAuthMech;
|
||||
|
@ -15,10 +16,10 @@ public class WildflyKeycloakServletExtension extends KeycloakServletExtension {
|
|||
protected static Logger log = Logger.getLogger(WildflyKeycloakServletExtension.class);
|
||||
|
||||
@Override
|
||||
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, KeycloakDeployment deployment,
|
||||
protected ServletKeycloakAuthMech createAuthenticationMechanism(DeploymentInfo deploymentInfo, AdapterDeploymentContext deploymentContext,
|
||||
UndertowUserSessionManagement userSessionManagement) {
|
||||
log.info("creating WildflyAuthenticationMechanism");
|
||||
return new WildflyAuthenticationMechanism(deployment, userSessionManagement, deploymentInfo.getConfidentialPortManager());
|
||||
return new WildflyAuthenticationMechanism(deploymentContext, userSessionManagement, deploymentInfo.getConfidentialPortManager());
|
||||
|
||||
}
|
||||
}
|
||||
|
|
2
pom.xml
2
pom.xml
|
@ -102,7 +102,7 @@
|
|||
<module>server</module>
|
||||
<module>timer</module>
|
||||
<module>bundled-war-example</module>
|
||||
<!-- <module>project-integrations</module> -->
|
||||
<module>project-integrations</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -17,11 +17,12 @@ import org.keycloak.representations.adapters.action.SessionStatsAction;
|
|||
import org.keycloak.representations.adapters.action.UserStats;
|
||||
import org.keycloak.representations.adapters.action.UserStatsAction;
|
||||
import org.keycloak.services.util.HttpClientBuilder;
|
||||
import org.keycloak.services.util.ResolveRelative;
|
||||
import org.keycloak.util.Time;
|
||||
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
@ -33,11 +34,11 @@ import java.util.Map;
|
|||
public class ResourceAdminManager {
|
||||
protected static Logger logger = Logger.getLogger(ResourceAdminManager.class);
|
||||
|
||||
public SessionStats getSessionStats(RealmModel realm, ApplicationModel application, boolean users) {
|
||||
public SessionStats getSessionStats(URI requestUri, RealmModel realm, ApplicationModel application, boolean users) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
return getSessionStats(realm, application, users, executor);
|
||||
return getSessionStats(requestUri, realm, application, users, executor);
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
|
@ -51,8 +52,8 @@ public class ResourceAdminManager {
|
|||
return new ApacheHttpClient4Executor(client);
|
||||
}
|
||||
|
||||
public SessionStats getSessionStats(RealmModel realm, ApplicationModel application, boolean users, ApacheHttpClient4Executor client) {
|
||||
String managementUrl = application.getManagementUrl();
|
||||
public SessionStats getSessionStats(URI requestUri, RealmModel realm, ApplicationModel application, boolean users, ApacheHttpClient4Executor client) {
|
||||
String managementUrl = getManagementUrl(requestUri, application);
|
||||
if (managementUrl != null) {
|
||||
SessionStatsAction adminAction = new SessionStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName());
|
||||
adminAction.setListUsers(users);
|
||||
|
@ -94,11 +95,19 @@ public class ResourceAdminManager {
|
|||
|
||||
}
|
||||
|
||||
public UserStats getUserStats(RealmModel realm, ApplicationModel application, UserModel user) {
|
||||
protected String getManagementUrl(URI requestUri, ApplicationModel application) {
|
||||
String mgmtUrl = application.getManagementUrl();
|
||||
|
||||
// this is to support relative admin urls when keycloak and applications are deployed on the same machine
|
||||
return ResolveRelative.resolveRelativeUri(requestUri, mgmtUrl);
|
||||
|
||||
}
|
||||
|
||||
public UserStats getUserStats(URI requestUri, RealmModel realm, ApplicationModel application, UserModel user) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
return getUserStats(realm, application, user, executor);
|
||||
return getUserStats(requestUri, realm, application, user, executor);
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
|
@ -106,8 +115,8 @@ public class ResourceAdminManager {
|
|||
}
|
||||
|
||||
|
||||
public UserStats getUserStats(RealmModel realm, ApplicationModel application, UserModel user, ApacheHttpClient4Executor client) {
|
||||
String managementUrl = application.getManagementUrl();
|
||||
public UserStats getUserStats(URI requestUri, RealmModel realm, ApplicationModel application, UserModel user, ApacheHttpClient4Executor client) {
|
||||
String managementUrl = getManagementUrl(requestUri, application);
|
||||
if (managementUrl != null) {
|
||||
UserStatsAction adminAction = new UserStatsAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, application.getName(), user.getId());
|
||||
String token = new TokenManager().encodeToken(realm, adminAction);
|
||||
|
@ -137,7 +146,7 @@ public class ResourceAdminManager {
|
|||
|
||||
}
|
||||
|
||||
public void logoutUser(RealmModel realm, UserModel user) {
|
||||
public void logoutUser(URI requestUri, RealmModel realm, UserModel user) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
|
@ -145,13 +154,13 @@ public class ResourceAdminManager {
|
|||
List<ApplicationModel> resources = realm.getApplications();
|
||||
logger.debugv("logging out {0} resources ", resources.size());
|
||||
for (ApplicationModel resource : resources) {
|
||||
logoutApplication(realm, resource, user.getId(), executor, 0);
|
||||
logoutApplication(requestUri, realm, resource, user.getId(), executor, 0);
|
||||
}
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
}
|
||||
public void logoutAll(RealmModel realm) {
|
||||
public void logoutAll(URI requestUri, RealmModel realm) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
|
@ -159,19 +168,19 @@ public class ResourceAdminManager {
|
|||
List<ApplicationModel> resources = realm.getApplications();
|
||||
logger.debugv("logging out {0} resources ", resources.size());
|
||||
for (ApplicationModel resource : resources) {
|
||||
logoutApplication(realm, resource, null, executor, realm.getNotBefore());
|
||||
logoutApplication(requestUri, realm, resource, null, executor, realm.getNotBefore());
|
||||
}
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public void logoutApplication(RealmModel realm, ApplicationModel resource, String user) {
|
||||
public void logoutApplication(URI requestUri, RealmModel realm, ApplicationModel resource, String user) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
resource.setNotBefore(Time.currentTime());
|
||||
logoutApplication(realm, resource, user, executor, resource.getNotBefore());
|
||||
logoutApplication(requestUri, realm, resource, user, executor, resource.getNotBefore());
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
|
@ -179,8 +188,8 @@ public class ResourceAdminManager {
|
|||
}
|
||||
|
||||
|
||||
protected boolean logoutApplication(RealmModel realm, ApplicationModel resource, String user, ApacheHttpClient4Executor client, int notBefore) {
|
||||
String managementUrl = resource.getManagementUrl();
|
||||
protected boolean logoutApplication(URI requestUri, RealmModel realm, ApplicationModel resource, String user, ApacheHttpClient4Executor client, int notBefore) {
|
||||
String managementUrl = getManagementUrl(requestUri, resource);
|
||||
if (managementUrl != null) {
|
||||
LogoutAction adminAction = new LogoutAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), user, notBefore);
|
||||
String token = new TokenManager().encodeToken(realm, adminAction);
|
||||
|
@ -205,32 +214,32 @@ public class ResourceAdminManager {
|
|||
}
|
||||
}
|
||||
|
||||
public void pushRealmRevocationPolicy(RealmModel realm) {
|
||||
public void pushRealmRevocationPolicy(URI requestUri, RealmModel realm) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
for (ApplicationModel application : realm.getApplications()) {
|
||||
pushRevocationPolicy(realm, application, realm.getNotBefore(), executor);
|
||||
pushRevocationPolicy(requestUri, realm, application, realm.getNotBefore(), executor);
|
||||
}
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public void pushApplicationRevocationPolicy(RealmModel realm, ApplicationModel application) {
|
||||
public void pushApplicationRevocationPolicy(URI requestUri, RealmModel realm, ApplicationModel application) {
|
||||
ApacheHttpClient4Executor executor = createExecutor();
|
||||
|
||||
try {
|
||||
pushRevocationPolicy(realm, application, application.getNotBefore(), executor);
|
||||
pushRevocationPolicy(requestUri, realm, application, application.getNotBefore(), executor);
|
||||
} finally {
|
||||
executor.getHttpClient().getConnectionManager().shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected boolean pushRevocationPolicy(RealmModel realm, ApplicationModel resource, int notBefore, ApacheHttpClient4Executor client) {
|
||||
protected boolean pushRevocationPolicy(URI requestUri, RealmModel realm, ApplicationModel resource, int notBefore, ApacheHttpClient4Executor client) {
|
||||
if (notBefore <= 0) return false;
|
||||
String managementUrl = resource.getManagementUrl();
|
||||
String managementUrl = getManagementUrl(requestUri, resource);
|
||||
if (managementUrl != null) {
|
||||
PushNotBeforeAction adminAction = new PushNotBeforeAction(TokenIdGenerator.generateId(), Time.currentTime() + 30, resource.getName(), notBefore);
|
||||
String token = new TokenManager().encodeToken(realm, adminAction);
|
||||
|
|
|
@ -56,6 +56,7 @@ import org.keycloak.services.messages.Messages;
|
|||
import org.keycloak.services.resources.flows.Flows;
|
||||
import org.keycloak.services.resources.flows.OAuthRedirect;
|
||||
import org.keycloak.services.resources.flows.Urls;
|
||||
import org.keycloak.services.util.ResolveRelative;
|
||||
import org.keycloak.services.validation.Validation;
|
||||
import org.keycloak.social.SocialLoader;
|
||||
import org.keycloak.social.SocialProvider;
|
||||
|
@ -512,9 +513,9 @@ public class AccountService {
|
|||
ApplicationModel application = realm.getApplicationByName(referrer);
|
||||
if (application != null) {
|
||||
if (referrerUri != null) {
|
||||
referrerUri = TokenService.verifyRedirectUri(referrerUri, application);
|
||||
referrerUri = TokenService.verifyRedirectUri(uriInfo, referrerUri, application);
|
||||
} else {
|
||||
referrerUri = application.getBaseUrl();
|
||||
referrerUri = ResolveRelative.resolveRelativeUri(uriInfo.getRequestUri(), application.getBaseUrl());
|
||||
}
|
||||
|
||||
if (referrerUri != null) {
|
||||
|
@ -523,7 +524,7 @@ public class AccountService {
|
|||
} else if (referrerUri != null) {
|
||||
ClientModel client = realm.getOAuthClient(referrer);
|
||||
if (client != null) {
|
||||
referrerUri = TokenService.verifyRedirectUri(referrerUri, application);
|
||||
referrerUri = TokenService.verifyRedirectUri(uriInfo, referrerUri, application);
|
||||
|
||||
if (referrerUri != null) {
|
||||
return new String[]{referrer, referrerUri};
|
||||
|
|
|
@ -290,7 +290,7 @@ public class SocialResource {
|
|||
logger.warn("Login requester not enabled.");
|
||||
return Flows.forms(realm, uriInfo).setError("Login requester not enabled.").createErrorPage();
|
||||
}
|
||||
redirectUri = TokenService.verifyRedirectUri(redirectUri, client);
|
||||
redirectUri = TokenService.verifyRedirectUri(uriInfo, redirectUri, client);
|
||||
if (redirectUri == null) {
|
||||
audit.error(Errors.INVALID_REDIRECT_URI);
|
||||
return Flows.forms(realm, uriInfo).setError("Invalid redirect_uri.").createErrorPage();
|
||||
|
|
|
@ -63,7 +63,9 @@ import javax.ws.rs.core.SecurityContext;
|
|||
import javax.ws.rs.core.UriBuilder;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
import javax.ws.rs.ext.Providers;
|
||||
import java.net.URI;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
@ -288,7 +290,7 @@ public class TokenService {
|
|||
return oauth.forwardToSecurityFailure("Login requester not enabled.");
|
||||
}
|
||||
|
||||
redirect = verifyRedirectUri(redirect, client);
|
||||
redirect = verifyRedirectUri(uriInfo, redirect, client);
|
||||
if (redirect == null) {
|
||||
audit.error(Errors.INVALID_REDIRECT_URI);
|
||||
return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
|
||||
|
@ -377,7 +379,7 @@ public class TokenService {
|
|||
return oauth.forwardToSecurityFailure("Login requester not enabled.");
|
||||
}
|
||||
|
||||
redirect = verifyRedirectUri(redirect, client);
|
||||
redirect = verifyRedirectUri(uriInfo, redirect, client);
|
||||
if (redirect == null) {
|
||||
audit.error(Errors.INVALID_REDIRECT_URI);
|
||||
return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
|
||||
|
@ -636,7 +638,7 @@ public class TokenService {
|
|||
audit.error(Errors.CLIENT_DISABLED);
|
||||
return oauth.forwardToSecurityFailure("Login requester not enabled.");
|
||||
}
|
||||
redirect = verifyRedirectUri(redirect, client);
|
||||
redirect = verifyRedirectUri(uriInfo, redirect, client);
|
||||
if (redirect == null) {
|
||||
audit.error(Errors.INVALID_REDIRECT_URI);
|
||||
return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
|
||||
|
@ -690,7 +692,7 @@ public class TokenService {
|
|||
return oauth.forwardToSecurityFailure("Login requester not enabled.");
|
||||
}
|
||||
|
||||
redirect = verifyRedirectUri(redirect, client);
|
||||
redirect = verifyRedirectUri(uriInfo, redirect, client);
|
||||
if (redirect == null) {
|
||||
audit.error(Errors.INVALID_REDIRECT_URI);
|
||||
return oauth.forwardToSecurityFailure("Invalid redirect_uri.");
|
||||
|
@ -721,7 +723,7 @@ public class TokenService {
|
|||
logger.infov("Logging out: {0}", user.getLoginName());
|
||||
authManager.expireIdentityCookie(realm, uriInfo);
|
||||
authManager.expireRememberMeCookie(realm, uriInfo);
|
||||
resourceAdminManager.logoutUser(realm, user);
|
||||
resourceAdminManager.logoutUser(uriInfo.getRequestUri(), realm, user);
|
||||
|
||||
audit.user(user).success();
|
||||
} else {
|
||||
|
@ -813,10 +815,11 @@ public class TokenService {
|
|||
return false;
|
||||
}
|
||||
|
||||
public static String verifyRedirectUri(String redirectUri, ClientModel client) {
|
||||
public static String verifyRedirectUri(UriInfo uriInfo, String redirectUri, ClientModel client) {
|
||||
Set<String> validRedirects = client.getRedirectUris();
|
||||
if (redirectUri == null) {
|
||||
return client.getRedirectUris().size() == 1 ? client.getRedirectUris().iterator().next() : null;
|
||||
} else if (client.getRedirectUris().isEmpty()) {
|
||||
return validRedirects.size() == 1 ? validRedirects.iterator().next() : null;
|
||||
} else if (validRedirects.isEmpty()) {
|
||||
if (client.isPublicClient()) {
|
||||
logger.error("Client redirect uri must be registered for public client");
|
||||
return null;
|
||||
|
@ -825,7 +828,22 @@ public class TokenService {
|
|||
} else {
|
||||
String r = redirectUri.indexOf('?') != -1 ? redirectUri.substring(0, redirectUri.indexOf('?')) : redirectUri;
|
||||
|
||||
boolean valid = matchesRedirects(client.getRedirectUris(), r);
|
||||
// If the valid redirect URI is relative (no scheme, host, port) then use the request's scheme, host, and port
|
||||
Set<String> resolveValidRedirects = new HashSet<String>();
|
||||
for (String validRedirect : validRedirects) {
|
||||
if (validRedirect.startsWith("/")) {
|
||||
URI baseUri = uriInfo.getBaseUri();
|
||||
String uri = baseUri.getScheme() + "://" + baseUri.getHost();
|
||||
if (baseUri.getPort() != -1) {
|
||||
uri += ":" + baseUri.getPort();
|
||||
}
|
||||
validRedirect = uri + validRedirect;
|
||||
logger.debugv("replacing relative valid redirect with: {0}", validRedirect);
|
||||
}
|
||||
resolveValidRedirects.add(validRedirect);
|
||||
}
|
||||
|
||||
boolean valid = matchesRedirects(resolveValidRedirects, r);
|
||||
|
||||
if (!valid && r.startsWith(Constants.INSTALLED_APP_URL) && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) {
|
||||
int i = r.indexOf(':', Constants.INSTALLED_APP_URL.length());
|
||||
|
@ -840,9 +858,8 @@ public class TokenService {
|
|||
|
||||
r = sb.toString();
|
||||
|
||||
valid = matchesRedirects(client.getRedirectUris(), r);
|
||||
valid = matchesRedirects(resolveValidRedirects, r);
|
||||
}
|
||||
|
||||
return valid ? redirectUri : null;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -204,7 +204,7 @@ public class ApplicationResource {
|
|||
@POST
|
||||
public void pushRevocation() {
|
||||
auth.requireManage();
|
||||
new ResourceAdminManager().pushApplicationRevocationPolicy(realm, application);
|
||||
new ResourceAdminManager().pushApplicationRevocationPolicy(uriInfo.getRequestUri(), realm, application);
|
||||
}
|
||||
|
||||
@Path("session-stats")
|
||||
|
@ -220,7 +220,7 @@ public class ApplicationResource {
|
|||
if (users) stats.setUsers(new HashMap<String, UserStats>());
|
||||
return stats;
|
||||
}
|
||||
SessionStats stats = new ResourceAdminManager().getSessionStats(realm, application, users);
|
||||
SessionStats stats = new ResourceAdminManager().getSessionStats(uriInfo.getRequestUri(), realm, application, users);
|
||||
if (stats == null) {
|
||||
logger.info("app returned null stats");
|
||||
} else {
|
||||
|
@ -234,7 +234,7 @@ public class ApplicationResource {
|
|||
@POST
|
||||
public void logoutAll() {
|
||||
auth.requireManage();
|
||||
new ResourceAdminManager().logoutApplication(realm, application, null);
|
||||
new ResourceAdminManager().logoutApplication(uriInfo.getRequestUri(), realm, application, null);
|
||||
}
|
||||
|
||||
@Path("logout-user/{username}")
|
||||
|
@ -245,7 +245,7 @@ public class ApplicationResource {
|
|||
if (user == null) {
|
||||
throw new NotFoundException("User not found");
|
||||
}
|
||||
new ResourceAdminManager().logoutApplication(realm, application, user.getId());
|
||||
new ResourceAdminManager().logoutApplication(uriInfo.getRequestUri(), realm, application, user.getId());
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -32,6 +32,7 @@ import javax.ws.rs.QueryParam;
|
|||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.UriInfo;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
@ -57,6 +58,9 @@ public class RealmAdminResource {
|
|||
@Context
|
||||
protected ProviderSession providers;
|
||||
|
||||
@Context
|
||||
protected UriInfo uriInfo;
|
||||
|
||||
public RealmAdminResource(RealmAuth auth, RealmModel realm, TokenManager tokenManager) {
|
||||
this.auth = auth;
|
||||
this.realm = realm;
|
||||
|
@ -145,14 +149,14 @@ public class RealmAdminResource {
|
|||
@POST
|
||||
public void pushRevocation() {
|
||||
auth.requireManage();
|
||||
new ResourceAdminManager().pushRealmRevocationPolicy(realm);
|
||||
new ResourceAdminManager().pushRealmRevocationPolicy(uriInfo.getRequestUri(), realm);
|
||||
}
|
||||
|
||||
@Path("logout-all")
|
||||
@POST
|
||||
public void logoutAll() {
|
||||
auth.requireManage();
|
||||
new ResourceAdminManager().logoutAll(realm);
|
||||
new ResourceAdminManager().logoutAll(uriInfo.getRequestUri(), realm);
|
||||
}
|
||||
|
||||
@Path("session-stats")
|
||||
|
@ -165,7 +169,7 @@ public class RealmAdminResource {
|
|||
Map<String, SessionStats> stats = new HashMap<String, SessionStats>();
|
||||
for (ApplicationModel applicationModel : realm.getApplications()) {
|
||||
if (applicationModel.getManagementUrl() == null) continue;
|
||||
SessionStats appStats = new ResourceAdminManager().getSessionStats(realm, applicationModel, false);
|
||||
SessionStats appStats = new ResourceAdminManager().getSessionStats(uriInfo.getRequestUri(), realm, applicationModel, false);
|
||||
stats.put(applicationModel.getName(), appStats);
|
||||
}
|
||||
return stats;
|
||||
|
|
|
@ -172,7 +172,7 @@ public class UsersResource {
|
|||
Map<String, UserStats> stats = new HashMap<String, UserStats>();
|
||||
for (ApplicationModel applicationModel : realm.getApplications()) {
|
||||
if (applicationModel.getManagementUrl() == null) continue;
|
||||
UserStats appStats = new ResourceAdminManager().getUserStats(realm, applicationModel, user);
|
||||
UserStats appStats = new ResourceAdminManager().getUserStats(uriInfo.getRequestUri(), realm, applicationModel, user);
|
||||
if (appStats == null) continue;
|
||||
if (appStats.isLoggedIn()) stats.put(applicationModel.getName(), appStats);
|
||||
}
|
||||
|
@ -189,7 +189,7 @@ public class UsersResource {
|
|||
}
|
||||
// set notBefore so that user will be forced to log in.
|
||||
user.setNotBefore(Time.currentTime());
|
||||
new ResourceAdminManager().logoutUser(realm, user);
|
||||
new ResourceAdminManager().logoutUser(uriInfo.getRequestUri(), realm, user);
|
||||
}
|
||||
|
||||
|
||||
|
|
20
services/src/main/java/org/keycloak/services/util/ResolveRelative.java
Executable file
20
services/src/main/java/org/keycloak/services/util/ResolveRelative.java
Executable file
|
@ -0,0 +1,20 @@
|
|||
package org.keycloak.services.util;
|
||||
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
|
||||
* @version $Revision: 1 $
|
||||
*/
|
||||
public class ResolveRelative {
|
||||
public static String resolveRelativeUri(URI requestUri, String url) {
|
||||
if (url == null || !url.startsWith("/")) return url;
|
||||
UriBuilder builder = UriBuilder.fromPath(url).host(requestUri.getHost());
|
||||
builder.scheme(requestUri.getScheme());
|
||||
if (requestUri.getPort() != -1) {
|
||||
builder.port(requestUri.getPort());
|
||||
}
|
||||
return builder.build().toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,156 @@
|
|||
/*
|
||||
* 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.OAuth2Constants;
|
||||
import org.keycloak.models.ApplicationModel;
|
||||
import org.keycloak.models.Constants;
|
||||
import org.keycloak.models.RealmModel;
|
||||
import org.keycloak.models.UserModel;
|
||||
import org.keycloak.representations.AccessToken;
|
||||
import org.keycloak.representations.adapters.action.SessionStats;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.services.managers.RealmManager;
|
||||
import org.keycloak.services.managers.TokenManager;
|
||||
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 javax.ws.rs.client.Client;
|
||||
import javax.ws.rs.client.ClientBuilder;
|
||||
import javax.ws.rs.client.WebTarget;
|
||||
import javax.ws.rs.core.GenericType;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
import java.net.URL;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Tests Undertow Adapter
|
||||
*
|
||||
* Also tests relative URIs in the adapter and valid redirect uris.
|
||||
* Also tests adapters not configured with public key
|
||||
*
|
||||
* @author <a href="mailto:bburke@redhat.com">Bill Burke</a>
|
||||
*/
|
||||
public class RelativeUriAdapterTest {
|
||||
|
||||
public static final String LOGIN_URL = "http://localhost:8081/auth/rest/realms/demo/tokens/login";
|
||||
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-relative.json"), RealmRepresentation.class);
|
||||
RealmModel realm = manager.importRealm(representation);
|
||||
|
||||
realmPublicKey = realm.getPublicKey();
|
||||
|
||||
URL url = getClass().getResource("/adapter-test/cust-app-keycloak-relative.json");
|
||||
deployApplication("customer-portal", "/customer-portal", CustomerServlet.class, url.getPath(), "user");
|
||||
url = getClass().getResource("/adapter-test/customer-db-keycloak-relative.json");
|
||||
deployApplication("customer-db", "/customer-db", CustomerDatabaseServlet.class, url.getPath(), "user");
|
||||
url = getClass().getResource("/adapter-test/product-keycloak-relative.json");
|
||||
deployApplication("product-portal", "/product-portal", ProductServlet.class, url.getPath(), "user");
|
||||
ApplicationModel adminConsole = adminRealm.getApplicationByName(Constants.ADMIN_CONSOLE_APPLICATION);
|
||||
TokenManager tm = new TokenManager();
|
||||
UserModel admin = adminRealm.getUser("admin");
|
||||
AccessToken token = tm.createClientAccessToken(null, adminRealm, adminConsole, admin);
|
||||
adminToken = tm.encodeToken(adminRealm, token);
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
public static String adminToken;
|
||||
|
||||
@Rule
|
||||
public WebRule webRule = new WebRule(this);
|
||||
|
||||
@WebResource
|
||||
protected WebDriver driver;
|
||||
|
||||
@WebResource
|
||||
protected OAuthClient oauth;
|
||||
|
||||
@WebResource
|
||||
protected LoginPage loginPage;
|
||||
|
||||
@Test
|
||||
public void testLoginSSOAndLogout() 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(LOGIN_URL));
|
||||
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 stats
|
||||
Client client = ClientBuilder.newClient();
|
||||
WebTarget adminTarget = client.target("http://localhost:8081/auth/rest/admin/realms/demo");
|
||||
Map<String, SessionStats> stats = adminTarget.path("session-stats").request()
|
||||
.header(HttpHeaders.AUTHORIZATION, "Bearer " + adminToken)
|
||||
.get(new GenericType<Map<String, SessionStats>>(){});
|
||||
|
||||
SessionStats custStats = stats.get("customer-portal");
|
||||
Assert.assertNotNull(custStats);
|
||||
Assert.assertEquals(1, custStats.getActiveSessions());
|
||||
SessionStats prodStats = stats.get("product-portal");
|
||||
Assert.assertNotNull(prodStats);
|
||||
Assert.assertEquals(1, prodStats.getActiveSessions());
|
||||
|
||||
client.close();
|
||||
|
||||
|
||||
// test logout
|
||||
|
||||
String logoutUri = UriBuilder.fromUri("http://localhost:8081/auth/rest/realms/demo/tokens/logout")
|
||||
.queryParam(OAuth2Constants.REDIRECT_URI, "http://localhost:8081/customer-portal").build().toString();
|
||||
driver.navigate().to(logoutUri);
|
||||
Assert.assertTrue(driver.getCurrentUrl().startsWith(LOGIN_URL));
|
||||
driver.navigate().to("http://localhost:8081/product-portal");
|
||||
Assert.assertTrue(driver.getCurrentUrl().startsWith(LOGIN_URL));
|
||||
driver.navigate().to("http://localhost:8081/customer-portal");
|
||||
Assert.assertTrue(driver.getCurrentUrl().startsWith(LOGIN_URL));
|
||||
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"realm": "demo",
|
||||
"resource": "customer-portal",
|
||||
"auth-server-url": "/auth",
|
||||
"ssl-not-required": true,
|
||||
"credentials": {
|
||||
"secret": "password"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"realm" : "demo",
|
||||
"resource" : "customer-db",
|
||||
"auth-server-url": "/auth",
|
||||
"ssl-not-required": true,
|
||||
"bearer-only" : true,
|
||||
"enable-cors" : true
|
||||
|
||||
}
|
120
testsuite/integration/src/test/resources/adapter-test/demorealm-relative.json
Executable file
120
testsuite/integration/src/test/resources/adapter-test/demorealm-relative.json
Executable file
|
@ -0,0 +1,120 @@
|
|||
{
|
||||
"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": "/customer-portal",
|
||||
"baseUrl": "/customer-portal",
|
||||
"redirectUris": [
|
||||
"/customer-portal/*"
|
||||
],
|
||||
"secret": "password"
|
||||
},
|
||||
{
|
||||
"name": "customer-portal-js",
|
||||
"enabled": true,
|
||||
"publicClient": true,
|
||||
"baseUrl": "/customer-portal-js",
|
||||
"redirectUris": [
|
||||
"/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": "/product-portal",
|
||||
"baseUrl": "/product-portal",
|
||||
"redirectUris": [
|
||||
"/product-portal/*"
|
||||
],
|
||||
"secret": "password"
|
||||
}
|
||||
],
|
||||
"oauthClients": [
|
||||
{
|
||||
"name": "third-party",
|
||||
"enabled": true,
|
||||
"redirectUris": [
|
||||
"/oauth-client/*",
|
||||
"/oauth-client-cdi/*"
|
||||
],
|
||||
"secret": "password"
|
||||
}
|
||||
],
|
||||
"applicationRoleMappings": {
|
||||
"account": [
|
||||
{
|
||||
"username": "bburke@redhat.com",
|
||||
"roles": ["manage-account"]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"realm" : "demo",
|
||||
"resource" : "product-portal",
|
||||
"auth-server-url" : "/auth",
|
||||
"ssl-not-required" : true,
|
||||
"credentials" : {
|
||||
"secret": "password"
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue