Search in sources :

Example 1 with KeycloakConfigResolver

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

the class JaxrsBearerTokenFilterImpl method start.

protected void start() {
    if (started) {
        throw new IllegalStateException("Filter already started. Make sure to specify just keycloakConfigResolver or keycloakConfigFile but not both");
    }
    if (keycloakConfigResolverClass != null) {
        Class<? extends KeycloakConfigResolver> resolverClass = loadResolverClass();
        try {
            KeycloakConfigResolver resolver = resolverClass.newInstance();
            log.info("Using " + resolver + " to resolve Keycloak configuration on a per-request basis.");
            this.deploymentContext = new AdapterDeploymentContext(resolver);
        } catch (Exception e) {
            throw new RuntimeException("Unable to instantiate resolver " + resolverClass);
        }
    } else {
        if (keycloakConfigFile == null) {
            throw new IllegalArgumentException("You need to specify either keycloakConfigResolverClass or keycloakConfigFile in configuration");
        }
        InputStream is = loadKeycloakConfigFile();
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is);
        deploymentContext = new AdapterDeploymentContext(kd);
        log.info("Keycloak is using a per-deployment configuration loaded from: " + keycloakConfigFile);
    }
    nodesRegistrationManagement = new NodesRegistrationManagement();
    started = true;
}
Also used : NodesRegistrationManagement(org.keycloak.adapters.NodesRegistrationManagement) KeycloakConfigResolver(org.keycloak.adapters.KeycloakConfigResolver) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 2 with KeycloakConfigResolver

use of org.keycloak.adapters.KeycloakConfigResolver 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 3 with KeycloakConfigResolver

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

the class AbstractKeycloakAuthenticatorValve method keycloakInit.

@SuppressWarnings("UseSpecificCatch")
public void keycloakInit() {
    // Possible scenarios:
    // 1) The deployment has a keycloak.config.resolver specified and it exists:
    // Outcome: adapter uses the resolver
    // 2) The deployment has a keycloak.config.resolver and isn't valid (doesn't exist, isn't a resolver, ...) :
    // Outcome: adapter is left unconfigured
    // 3) The deployment doesn't have a keycloak.config.resolver , but has a keycloak.json (or equivalent)
    // Outcome: adapter uses it
    // 4) The deployment doesn't have a keycloak.config.resolver nor keycloak.json (or equivalent)
    // Outcome: adapter is left unconfigured
    String configResolverClass = context.getServletContext().getInitParameter("keycloak.config.resolver");
    if (configResolverClass != null) {
        try {
            KeycloakConfigResolver configResolver = (KeycloakConfigResolver) context.getLoader().getClassLoader().loadClass(configResolverClass).newInstance();
            deploymentContext = new AdapterDeploymentContext(configResolver);
            log.debugv("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
        } catch (Exception ex) {
            log.errorv("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", configResolverClass, ex.getMessage());
            deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment());
        }
    } else {
        InputStream configInputStream = getConfigInputStream(context);
        KeycloakDeployment kd;
        if (configInputStream == null) {
            log.warn("No adapter configuration. Keycloak is unconfigured and will deny all requests.");
            kd = new KeycloakDeployment();
        } else {
            kd = KeycloakDeploymentBuilder.build(configInputStream);
        }
        deploymentContext = new AdapterDeploymentContext(kd);
        log.debug("Keycloak is using a per-deployment configuration.");
    }
    context.getServletContext().setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    AbstractAuthenticatedActionsValve actions = createAuthenticatedActionsValve(deploymentContext, getNext(), getContainer());
    setNext(actions);
    nodesRegistrationManagement = new NodesRegistrationManagement();
}
Also used : NodesRegistrationManagement(org.keycloak.adapters.NodesRegistrationManagement) KeycloakConfigResolver(org.keycloak.adapters.KeycloakConfigResolver) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 4 with KeycloakConfigResolver

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

the class KeycloakConfigurationServletListener method contextInitialized.

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();
    String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
    KeycloakConfigResolver configResolver;
    AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) servletContext.getAttribute(AdapterDeploymentContext.class.getName());
    if (deploymentContext == null) {
        if (configResolverClass != null) {
            try {
                configResolver = (KeycloakConfigResolver) servletContext.getClassLoader().loadClass(configResolverClass).newInstance();
                deploymentContext = new AdapterDeploymentContext(configResolver);
            } catch (Exception ex) {
                deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment());
            }
        } else {
            InputStream is = getConfigInputStream(servletContext);
            KeycloakDeployment deployment;
            if (is == null) {
                deployment = new KeycloakDeployment();
            } else {
                deployment = KeycloakDeploymentBuilder.build(is);
            }
            deploymentContext = new AdapterDeploymentContext(deployment);
        }
    }
    servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE, deploymentContext);
    servletContext.setAttribute(ADAPTER_DEPLOYMENT_CONTEXT_ATTRIBUTE_ELYTRON, deploymentContext);
}
Also used : KeycloakConfigResolver(org.keycloak.adapters.KeycloakConfigResolver) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) ServletContext(javax.servlet.ServletContext) FileNotFoundException(java.io.FileNotFoundException)

Example 5 with KeycloakConfigResolver

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

the class KeycloakServletExtension method handleDeployment.

@Override
@SuppressWarnings("UseSpecificCatch")
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
    if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK") && deploymentContext == null) {
        log.debug("auth-method is not keycloak!");
        return;
    }
    log.debug("KeycloakServletException initialization");
    // Possible scenarios:
    // 1) The deployment has a keycloak.config.resolver specified and it exists:
    // Outcome: adapter uses the resolver
    // 2) The deployment has a keycloak.config.resolver and isn't valid (doesn't exist, isn't a resolver, ...) :
    // Outcome: adapter is left unconfigured
    // 3) The deployment doesn't have a keycloak.config.resolver , but has a keycloak.json (or equivalent)
    // Outcome: adapter uses it
    // 4) The deployment doesn't have a keycloak.config.resolver nor keycloak.json (or equivalent)
    // Outcome: adapter is left unconfigured
    AdapterDeploymentContext deploymentContext = this.deploymentContext;
    if (deploymentContext == null) {
        KeycloakConfigResolver configResolver;
        String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
        if (configResolverClass != null) {
            try {
                configResolver = (KeycloakConfigResolver) deploymentInfo.getClassLoader().loadClass(configResolverClass).newInstance();
                deploymentContext = new AdapterDeploymentContext(configResolver);
                log.info("Using " + configResolverClass + " to resolve Keycloak configuration on a per-request basis.");
            } catch (Exception ex) {
                log.warn("The specified resolver " + configResolverClass + " could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: " + ex.getMessage());
                deploymentContext = new AdapterDeploymentContext(new KeycloakDeployment());
            }
        } else {
            InputStream is = getConfigInputStream(servletContext);
            final KeycloakDeployment deployment;
            if (is == null) {
                log.warn("No adapter configuration.  Keycloak is unconfigured and will deny all requests.");
                deployment = new KeycloakDeployment();
            } else {
                deployment = KeycloakDeploymentBuilder.build(is);
            }
            deploymentContext = new AdapterDeploymentContext(deployment);
            log.debug("Keycloak is using a per-deployment configuration.");
        }
    } else {
        deploymentContext = this.deploymentContext;
    }
    servletContext.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement();
    final NodesRegistrationManagement nodesRegistrationManagement = new NodesRegistrationManagement();
    final ServletKeycloakAuthMech mech = createAuthenticationMechanism(deploymentInfo, deploymentContext, userSessionManagement, nodesRegistrationManagement);
    UndertowAuthenticatedActionsHandler.Wrapper actions = new UndertowAuthenticatedActionsHandler.Wrapper(deploymentContext);
    // setup handlers
    deploymentInfo.addOuterHandlerChainWrapper(new ServletPreAuthActionsHandler.Wrapper(deploymentContext, userSessionManagement));
    deploymentInfo.addAuthenticationMechanism("KEYCLOAK", new AuthenticationMechanismFactory() {

        @Override
        public AuthenticationMechanism create(String s, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
            return mech;
        }
    });
    // authentication
    // handles authenticated actions and cors.
    deploymentInfo.addInnerHandlerChainWrapper(actions);
    deploymentInfo.setIdentityManager(new IdentityManager() {

        @Override
        public Account verify(Account account) {
            return account;
        }

        @Override
        public Account verify(String id, Credential credential) {
            throw new IllegalStateException("Should never be called in Keycloak flow");
        }

        @Override
        public Account verify(Credential credential) {
            throw new IllegalStateException("Should never be called in Keycloak flow");
        }
    });
    ServletSessionConfig cookieConfig = deploymentInfo.getServletSessionConfig();
    if (cookieConfig == null) {
        cookieConfig = new ServletSessionConfig();
    }
    if (cookieConfig.getPath() == null) {
        log.debug("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
        cookieConfig.setPath(deploymentInfo.getContextPath());
        deploymentInfo.setServletSessionConfig(cookieConfig);
    }
    ChangeSessionId.turnOffChangeSessionIdOnLogin(deploymentInfo);
    deploymentInfo.addListener(new ListenerInfo(UndertowNodesRegistrationManagementWrapper.class, new InstanceFactory<UndertowNodesRegistrationManagementWrapper>() {

        @Override
        public InstanceHandle<UndertowNodesRegistrationManagementWrapper> createInstance() throws InstantiationException {
            UndertowNodesRegistrationManagementWrapper listener = new UndertowNodesRegistrationManagementWrapper(nodesRegistrationManagement);
            return new ImmediateInstanceHandle<UndertowNodesRegistrationManagementWrapper>(listener);
        }
    }));
}
Also used : Account(io.undertow.security.idm.Account) IdentityManager(io.undertow.security.idm.IdentityManager) NodesRegistrationManagement(org.keycloak.adapters.NodesRegistrationManagement) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) Credential(io.undertow.security.idm.Credential) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AuthenticationMechanism(io.undertow.security.api.AuthenticationMechanism) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) FileNotFoundException(java.io.FileNotFoundException) FormParserFactory(io.undertow.server.handlers.form.FormParserFactory) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) ListenerInfo(io.undertow.servlet.api.ListenerInfo) InstanceFactory(io.undertow.servlet.api.InstanceFactory) KeycloakConfigResolver(org.keycloak.adapters.KeycloakConfigResolver) AuthenticationMechanismFactory(io.undertow.security.api.AuthenticationMechanismFactory)

Aggregations

KeycloakConfigResolver (org.keycloak.adapters.KeycloakConfigResolver)6 KeycloakDeployment (org.keycloak.adapters.KeycloakDeployment)6 FileInputStream (java.io.FileInputStream)5 FileNotFoundException (java.io.FileNotFoundException)5 InputStream (java.io.InputStream)5 AdapterDeploymentContext (org.keycloak.adapters.AdapterDeploymentContext)5 NodesRegistrationManagement (org.keycloak.adapters.NodesRegistrationManagement)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 ServletException (javax.servlet.ServletException)2 AuthenticationMechanism (io.undertow.security.api.AuthenticationMechanism)1 AuthenticationMechanismFactory (io.undertow.security.api.AuthenticationMechanismFactory)1 Account (io.undertow.security.idm.Account)1 Credential (io.undertow.security.idm.Credential)1 IdentityManager (io.undertow.security.idm.IdentityManager)1 FormParserFactory (io.undertow.server.handlers.form.FormParserFactory)1 InstanceFactory (io.undertow.servlet.api.InstanceFactory)1 ListenerInfo (io.undertow.servlet.api.ListenerInfo)1 ServletSessionConfig (io.undertow.servlet.api.ServletSessionConfig)1 ImmediateInstanceHandle (io.undertow.servlet.util.ImmediateInstanceHandle)1