Search in sources :

Example 26 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.

the class KeycloakOIDCFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    log.fine("Keycloak OIDC Filter");
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (shouldSkip(request)) {
        chain.doFilter(req, res);
        return;
    }
    OIDCServletHttpFacade facade = new OIDCServletHttpFacade(request, response);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        response.sendError(403);
        log.fine("deployment not configured");
        return;
    }
    PreAuthActionsHandler preActions = new PreAuthActionsHandler(new IdMapperUserSessionManagement(), deploymentContext, facade);
    if (preActions.handleRequest()) {
        // System.err.println("**************** preActions.handleRequest happened!");
        return;
    }
    nodesRegistrationManagement.tryRegister(deployment);
    OIDCFilterSessionStore tokenStore = new OIDCFilterSessionStore(request, facade, 100000, deployment, idMapper);
    tokenStore.checkCurrentToken();
    FilterRequestAuthenticator authenticator = new FilterRequestAuthenticator(deployment, tokenStore, facade, request, 8443);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        log.fine("AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade);
        if (actions.handledRequest()) {
            return;
        } else {
            HttpServletRequestWrapper wrapper = tokenStore.buildWrapper();
            chain.doFilter(wrapper, res);
            return;
        }
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        log.fine("challenge");
        challenge.challenge(facade);
        return;
    }
    response.sendError(403);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticatedActionsHandler(org.keycloak.adapters.AuthenticatedActionsHandler) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthOutcome(org.keycloak.adapters.spi.AuthOutcome) PreAuthActionsHandler(org.keycloak.adapters.PreAuthActionsHandler)

Example 27 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.

the class KeycloakOIDCFilter method init.

@Override
public void init(final FilterConfig filterConfig) throws ServletException {
    String skipPatternDefinition = filterConfig.getInitParameter(SKIP_PATTERN_PARAM);
    if (skipPatternDefinition != null) {
        skipPattern = Pattern.compile(skipPatternDefinition, Pattern.DOTALL);
    }
    String idMapperClassName = filterConfig.getInitParameter(ID_MAPPER_PARAM);
    if (idMapperClassName != null) {
        try {
            final Class<?> idMapperClass = getClass().getClassLoader().loadClass(idMapperClassName);
            final Constructor<?> idMapperConstructor = idMapperClass.getDeclaredConstructor();
            Object idMapperInstance = null;
            // for KEYCLOAK-13745 test
            if (idMapperConstructor.getModifiers() == Modifier.PRIVATE) {
                idMapperInstance = idMapperClass.getMethod("getInstance").invoke(null);
            } else {
                idMapperInstance = idMapperConstructor.newInstance();
            }
            if (idMapperInstance instanceof SessionIdMapper) {
                this.idMapper = (SessionIdMapper) idMapperInstance;
            } else {
                log.log(Level.WARNING, "SessionIdMapper class {0} is not instance of org.keycloak.adapters.spi.SessionIdMapper", idMapperClassName);
            }
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            log.log(Level.WARNING, "SessionIdMapper class could not be instanced", e);
        }
    }
    if (definedconfigResolver != null) {
        deploymentContext = new AdapterDeploymentContext(definedconfigResolver);
        log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", definedconfigResolver.getClass());
    } else {
        String configResolverClass = filterConfig.getInitParameter(CONFIG_RESOLVER_PARAM);
        if (configResolverClass != null) {
            try {
                KeycloakConfigResolver configResolver = (KeycloakConfigResolver) getClass().getClassLoader().loadClass(configResolverClass).newInstance();
                deploymentContext = new AdapterDeploymentContext(configResolver);
                log.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
            } catch (Exception ex) {
                log.log(Level.FINE, "The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() });
                deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment());
            }
        } else {
            String fp = filterConfig.getInitParameter(CONFIG_FILE_PARAM);
            InputStream is = null;
            if (fp != null) {
                try {
                    is = new FileInputStream(fp);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            } else {
                String path = "/WEB-INF/keycloak.json";
                String pathParam = filterConfig.getInitParameter(CONFIG_PATH_PARAM);
                if (pathParam != null)
                    path = pathParam;
                is = filterConfig.getServletContext().getResourceAsStream(path);
            }
            KeycloakDeployment kd = createKeycloakDeploymentFrom(is);
            deploymentContext = new AdapterDeploymentContext(kd);
            log.fine("Keycloak is using a per-deployment configuration.");
        }
    }
    filterConfig.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    nodesRegistrationManagement = new NodesRegistrationManagement();
}
Also used : NodesRegistrationManagement(org.keycloak.adapters.NodesRegistrationManagement) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) FileInputStream(java.io.FileInputStream) KeycloakConfigResolver(org.keycloak.adapters.KeycloakConfigResolver) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) InMemorySessionIdMapper(org.keycloak.adapters.spi.InMemorySessionIdMapper) SessionIdMapper(org.keycloak.adapters.spi.SessionIdMapper)

Example 28 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.

the class HierarchicalPathBasedKeycloakConfigResolver method resolve.

@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    // we cached all available deployments initially and now we'll try to check them from
    // most specific to most general
    URI uri = URI.create(request.getURI());
    String path = uri.getPath();
    if (path != null) {
        while (path.startsWith("/")) {
            path = path.substring(1);
        }
        String[] segments = path.split("/");
        List<String> paths = collectPaths(segments);
        for (String pathFragment : paths) {
            KeycloakDeployment cachedDeployment = super.getCachedDeployment(pathFragment);
            if (cachedDeployment != null) {
                return cachedDeployment;
            }
        }
    }
    throw new IllegalStateException("Can't find Keycloak configuration related to URI path " + uri);
}
Also used : KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) URI(java.net.URI)

Example 29 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.

the class PathBasedKeycloakConfigResolver method cacheConfiguration.

private boolean cacheConfiguration(String key, File config) {
    try {
        InputStream is = new FileInputStream(config);
        KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(is);
        cache.put(key, deployment);
        return true;
    } catch (FileNotFoundException | RuntimeException e) {
        log.warn("Can't cache " + config + ": " + e.getMessage(), e);
        return false;
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream)

Example 30 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment in project keycloak by keycloak.

the class HierarchicalPathBasedKeycloakConfigResolverTest method populate.

@SuppressWarnings("unchecked")
private PathBasedKeycloakConfigResolver populate(PathBasedKeycloakConfigResolver resolver, boolean fallback) throws Exception {
    Field f = PathBasedKeycloakConfigResolver.class.getDeclaredField("cache");
    f.setAccessible(true);
    Map<String, KeycloakDeployment> cache = (Map<String, KeycloakDeployment>) f.get(resolver);
    cache.clear();
    cache.put("a-b-c-d-e", newKeycloakDeployment("a-b-c-d-e"));
    cache.put("a-b-c-d", newKeycloakDeployment("a-b-c-d"));
    cache.put("a-b-c", newKeycloakDeployment("a-b-c"));
    cache.put("a-b", newKeycloakDeployment("a-b"));
    cache.put("a", newKeycloakDeployment("a"));
    if (fallback) {
        cache.put("", newKeycloakDeployment(""));
    }
    return resolver;
}
Also used : Field(java.lang.reflect.Field) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) Map(java.util.Map)

Aggregations

KeycloakDeployment (org.keycloak.adapters.KeycloakDeployment)69 Test (org.junit.Test)21 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)21 PolicyEnforcer (org.keycloak.adapters.authorization.PolicyEnforcer)20 AuthorizationContext (org.keycloak.AuthorizationContext)16 OIDCHttpFacade (org.keycloak.adapters.OIDCHttpFacade)14 RefreshableKeycloakSecurityContext (org.keycloak.adapters.RefreshableKeycloakSecurityContext)12 AdapterDeploymentContext (org.keycloak.adapters.AdapterDeploymentContext)11 OAuthClient (org.keycloak.testsuite.util.OAuthClient)11 AdapterTokenStore (org.keycloak.adapters.AdapterTokenStore)10 InputStream (java.io.InputStream)9 KeycloakSecurityContext (org.keycloak.KeycloakSecurityContext)9 AuthenticatedActionsHandler (org.keycloak.adapters.AuthenticatedActionsHandler)9 FileInputStream (java.io.FileInputStream)7 FileNotFoundException (java.io.FileNotFoundException)7 HashMap (java.util.HashMap)7 KeycloakConfigResolver (org.keycloak.adapters.KeycloakConfigResolver)6 AuthChallenge (org.keycloak.adapters.spi.AuthChallenge)6 AuthOutcome (org.keycloak.adapters.spi.AuthOutcome)6 List (java.util.List)5