Java Code Examples for org.keycloak.adapters.spi.HttpFacade#Request

The following examples show how to use org.keycloak.adapters.spi.HttpFacade#Request . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SamlMultiTenantResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public SamlDeployment resolve(HttpFacade.Request request) {
    String realm = request.getQueryParamValue("realm");
    if (realm == null) {
        throw new IllegalStateException("Not able to resolve realm from the request path!");
    }

    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/" + realm + "-keycloak-saml.xml");
    if (is == null) {
        throw new IllegalStateException("Not able to find the file /" + realm + "-keycloak-saml.xml");
    }

    ResourceLoader loader = new ResourceLoader() {
        @Override
        public InputStream getResourceAsStream(String path) {
            return Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
        }
    };

    try {
        return new DeploymentBuilder().build(is, loader);
    } catch (ParsingException e) {
        throw new IllegalStateException("Cannot load SAML deployment", e);
    }
}
 
Example 2
Source File: MultiTenantResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KeycloakDeployment resolve(HttpFacade.Request request) {

    String path = request.getURI();
    int multitenantIndex = path.indexOf("multi-tenant/");
    if (multitenantIndex == -1) {
        throw new IllegalStateException("Not able to resolve realm from the request path!");
    }

    String realm = path.substring(path.indexOf("multi-tenant/")).split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }
    
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/" + realm + "-keycloak.json");

    if (is == null) {
        throw new IllegalStateException("Not able to find the file /" + realm + "-keycloak.json");
    }

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(is);
    return deployment;
}
 
Example 3
Source File: BundleBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected KeycloakDeployment findDeployment(HttpFacade.Request request) {
    if (bundleContext == null) {
        throw new IllegalStateException("bundleContext must be set for BundleBasedKeycloakConfigResolver!");
    }

    URL url = bundleContext.getBundle().getResource(configLocation);
    if (url == null) {
        throw new IllegalStateException("Failed to find the file " + configLocation + " on classpath.");
    }

    try {
        InputStream is = url.openStream();
        return KeycloakDeploymentBuilder.build(is);
    } catch (IOException ioe) {
        throw new IllegalStateException("Error reading file' " + configLocation + "' from bundle classpath.", ioe);
    }
}
 
Example 4
Source File: AtlasSecurityConfig.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Bean
protected AdapterDeploymentContext adapterDeploymentContext() throws Exception {
    AdapterDeploymentContextFactoryBean factoryBean;
    String fileName = configuration.getString("atlas.authentication.method.keycloak.file");
    if (fileName != null && !fileName.isEmpty()) {
        keycloakConfigFileResource = new FileSystemResource(fileName);
        factoryBean = new AdapterDeploymentContextFactoryBean(keycloakConfigFileResource);
    } else {
        Configuration conf = configuration.subset("atlas.authentication.method.keycloak");
        AdapterConfig cfg = new AdapterConfig();
        cfg.setRealm(conf.getString("realm", "atlas.com"));
        cfg.setAuthServerUrl(conf.getString("auth-server-url", "https://localhost/auth"));
        cfg.setResource(conf.getString("resource", "none"));

        Map<String,Object> credentials = new HashMap<>();
        credentials.put("secret", conf.getString("credentials-secret", "nosecret"));
        cfg.setCredentials(credentials);
        KeycloakDeployment dep = KeycloakDeploymentBuilder.build(cfg);
        factoryBean = new AdapterDeploymentContextFactoryBean(new KeycloakConfigResolver() {
            @Override
            public KeycloakDeployment resolve(HttpFacade.Request request) {
                return dep;
            }
        });
    }

    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example 5
Source File: DolphinKeycloakConfigResolver.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
public KeycloakDeployment resolve(final HttpFacade.Request request) {
    Assert.requireNonNull(request, "request");

    final String realmName = Optional.ofNullable(request.getHeader(REALM_NAME_HEADER)).
            orElse(configuration.getRealmName());
    final String applicationName = Optional.ofNullable(request.getHeader(APPLICATION_NAME_HEADER)).
            orElse(configuration.getApplicationName());
    final String authEndPoint = configuration.getAuthEndpoint();
    final boolean cors = configuration.isCors();

    Optional.ofNullable(realmName).orElseThrow(() -> new SecurityException("Realm name for security check is not configured!"));
    Optional.ofNullable(applicationName).orElseThrow(() -> new SecurityException("Application name for security check is not configured!"));
    Optional.ofNullable(authEndPoint).orElseThrow(() -> new SecurityException("Auth endpoint for security check is not configured!"));

    LOG.debug("Defined Keycloak AdapterConfig for request against realm '" +realmName + "' and app '" + applicationName + "'");

    final AdapterConfig adapterConfig = new AdapterConfig();
    LOG.debug("Checking if realm '" +realmName + "' is allowed");
    if(isRealmAllowed(realmName)){
        adapterConfig.setRealm(realmName);
    }else{
        if(LOG.isDebugEnabled()) {
            final String allowedRealms = configuration.getRealmNames().stream().reduce("", (a, b) -> a + "," + b);
            LOG.debug("Realm '" + realmName + "' is not allowed! Allowed realms are {}", allowedRealms);
        }
        throw new SecurityException("Access Denied! The given realm is not in the allowed realms.");
    }

    adapterConfig.setResource(applicationName);
    adapterConfig.setAuthServerUrl(authEndPoint);
    adapterConfig.setCors(cors);

    Optional.ofNullable(request.getHeader(BEARER_ONLY_HEADER)).
            ifPresent(v -> adapterConfig.setBearerOnly(true));

    return KeycloakDeploymentBuilder.build(adapterConfig);
}
 
Example 6
Source File: PathBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a context path from given {@link HttpFacade.Request}. For default context, first path segment
 * is returned.
 * @param request
 * @return
 */
private String getDeploymentKeyForURI(HttpFacade.Request request) {
    String uri = request.getURI();
    String relativePath = request.getRelativePath();
    String webContext = null;
    if (relativePath == null || !uri.contains(relativePath)) {
        String[] urlTokens = uri.split("/");
        if (urlTokens.length <  4) {
            throw new IllegalStateException("Not able to determine the web-context to load the correspondent keycloak.json file");
        }

        webContext = urlTokens[3];
    } else {
        URI parsedURI = URI.create(uri);
        String path = parsedURI.getPath();
        if (path.contains(relativePath)) {
            path = path.substring(0, path.indexOf(relativePath));
        }
        while (path.startsWith("/")) {
            path = path.substring(1);
        }
        webContext = path;
        if ("".equals(webContext)) {
            path = relativePath;
            while (path.startsWith("/")) {
                path = path.substring(1);
            }
            if (path.contains("/")) {
                path = path.substring(0, path.indexOf("/"));
            }
            webContext = path;
        }
    }

    return webContext;
}
 
Example 7
Source File: BundleBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public KeycloakDeployment resolve(HttpFacade.Request request) {
    if (cachedDeployment != null) {
        return cachedDeployment;
    } else {
        cachedDeployment = findDeployment(request);
        return cachedDeployment;
    }
}
 
Example 8
Source File: RequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean isAutodetectedBearerOnly(HttpFacade.Request request) {
    if (!deployment.isAutodetectBearerOnly()) return false;

    String headerValue = facade.getRequest().getHeader("X-Requested-With");
    if (headerValue != null && headerValue.equalsIgnoreCase("XMLHttpRequest")) {
        return true;
    }

    headerValue = facade.getRequest().getHeader("Faces-Request");
    if (headerValue != null && headerValue.startsWith("partial/")) {
        return true;
    }

    headerValue = facade.getRequest().getHeader("SOAPAction");
    if (headerValue != null) {
        return true;
    }

    List<String> accepts = facade.getRequest().getHeaders("Accept");
    if (accepts == null) accepts = Collections.emptyList();

    for (String accept : accepts) {
        if (accept.contains("text/html") || accept.contains("text/*") || accept.contains("*/*")) {
            return false;
        }
    }

    return true;
}
 
Example 9
Source File: AdapterDeploymentContextFactoryBeanTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakConfigResolver getKeycloakConfigResolver() {
    return new KeycloakConfigResolver() {
        @Override
        public KeycloakDeployment resolve(HttpFacade.Request facade) {
            return null;
        }
    };
}
 
Example 10
Source File: EcpAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean canHandle(HttpFacade httpFacade) {
    HttpFacade.Request request = httpFacade.getRequest();
    String acceptHeader = request.getHeader("Accept");
    String contentTypeHeader = request.getHeader("Content-Type");

    return (acceptHeader != null && acceptHeader.contains(PAOS_CONTENT_TYPE) && request.getHeader(PAOS_HEADER) != null)
            || (contentTypeHeader != null && contentTypeHeader.contains(PAOS_CONTENT_TYPE));
}
 
Example 11
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected boolean isAutodetectedBearerOnly(HttpFacade.Request request) {
    if (!deployment.isAutodetectBearerOnly()) return false;

    String headerValue = facade.getRequest().getHeader(GeneralConstants.HTTP_HEADER_X_REQUESTED_WITH);
    if (headerValue != null && headerValue.equalsIgnoreCase("XMLHttpRequest")) {
        return true;
    }

    headerValue = facade.getRequest().getHeader("Faces-Request");
    if (headerValue != null && headerValue.startsWith("partial/")) {
        return true;
    }

    headerValue = facade.getRequest().getHeader("SOAPAction");
    if (headerValue != null) {
        return true;
    }

    List<String> accepts = facade.getRequest().getHeaders("Accept");
    if (accepts == null) accepts = Collections.emptyList();

    for (String accept : accepts) {
        if (accept.contains("text/html") || accept.contains("text/*") || accept.contains("*/*")) {
            return false;
        }
    }

    return true;
}
 
Example 12
Source File: KeycloakConfiguration.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Override
public KeycloakDeployment resolve(HttpFacade.Request request) {
    return loadKeycloakDeployment();
}
 
Example 13
Source File: JaxrsHttpFacade.java    From hammock with Apache License 2.0 4 votes vote down vote up
@Override
public HttpFacade.Request getRequest() {
    return requestFacade;
}
 
Example 14
Source File: KeycloakSpringConfigResolverWrapper.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public KeycloakDeployment resolve(HttpFacade.Request facade) {
    return delegate.resolve(facade);
}