Search in sources :

Example 51 with KeycloakDeployment

use of org.keycloak.adapters.KeycloakDeployment 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)

Example 52 with KeycloakDeployment

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

the class ServletKeycloakAuthMech method authenticate.

@Override
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    UndertowHttpFacade facade = createFacade(exchange);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (!deployment.isConfigured()) {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    nodesRegistrationManagement.tryRegister(deployment);
    RequestAuthenticator authenticator = createRequestAuthenticator(deployment, exchange, securityContext, facade);
    return keycloakAuthenticate(exchange, securityContext, authenticator);
}
Also used : RequestAuthenticator(org.keycloak.adapters.RequestAuthenticator) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment)

Example 53 with KeycloakDeployment

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

the class KeycloakHttpServerAuthenticationMechanism method evaluateRequest.

@Override
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
    LOGGER.debugf("Evaluating request for path [%s]", request.getRequestURI());
    AdapterDeploymentContext deploymentContext = getDeploymentContext(request);
    if (deploymentContext == null) {
        LOGGER.debugf("Ignoring request for path [%s] from mechanism [%s]. No deployment context found.", request.getRequestURI(), getMechanismName());
        request.noAuthenticationInProgress();
        return;
    }
    ElytronHttpFacade httpFacade = new ElytronHttpFacade(request, deploymentContext, callbackHandler);
    KeycloakDeployment deployment = httpFacade.getDeployment();
    if (!deployment.isConfigured()) {
        request.noAuthenticationInProgress();
        return;
    }
    RequestAuthenticator authenticator = createRequestAuthenticator(request, httpFacade, deployment);
    httpFacade.getTokenStore().checkCurrentToken();
    if (preActions(httpFacade, deploymentContext)) {
        LOGGER.debugf("Pre-actions has aborted the evaluation of [%s]", request.getRequestURI());
        httpFacade.authenticationInProgress();
        return;
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (AuthOutcome.AUTHENTICATED.equals(outcome)) {
        if (new AuthenticatedActionsHandler(deployment, httpFacade).handledRequest()) {
            httpFacade.authenticationInProgress();
        } else {
            httpFacade.authenticationComplete();
        }
        return;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        httpFacade.noAuthenticationInProgress(challenge);
        return;
    }
    if (AuthOutcome.FAILED.equals(outcome)) {
        httpFacade.getResponse().setStatus(403);
        httpFacade.authenticationFailed();
        return;
    }
    httpFacade.noAuthenticationInProgress();
}
Also used : AuthenticatedActionsHandler(org.keycloak.adapters.AuthenticatedActionsHandler) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) RequestAuthenticator(org.keycloak.adapters.RequestAuthenticator) AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) AuthOutcome(org.keycloak.adapters.spi.AuthOutcome)

Example 54 with KeycloakDeployment

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

the class AbstractUndertowKeycloakAuthMech method registerNotifications.

protected void registerNotifications(final SecurityContext securityContext) {
    final NotificationReceiver logoutReceiver = new NotificationReceiver() {

        @Override
        public void handleNotification(SecurityNotification notification) {
            if (notification.getEventType() != SecurityNotification.EventType.LOGGED_OUT)
                return;
            HttpServerExchange exchange = notification.getExchange();
            UndertowHttpFacade facade = createFacade(exchange);
            KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
            KeycloakSecurityContext ksc = exchange.getAttachment(OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY);
            if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
                ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
            }
            AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
            tokenStore.logout();
        }
    };
    securityContext.registerNotificationReceiver(logoutReceiver);
}
Also used : HttpServerExchange(io.undertow.server.HttpServerExchange) NotificationReceiver(io.undertow.security.api.NotificationReceiver) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) AdapterTokenStore(org.keycloak.adapters.AdapterTokenStore) SecurityNotification(io.undertow.security.api.SecurityNotification)

Example 55 with KeycloakDeployment

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

the class AbstractAuthenticatedActionsValve method invoke.

@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    log.debugv("AuthenticatedActionsValve.invoke {0}", request.getRequestURI());
    CatalinaHttpFacade facade = new OIDCCatalinaHttpFacade(request, response);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment != null && deployment.isConfigured()) {
        AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, new OIDCCatalinaHttpFacade(request, response));
        if (handler.handledRequest()) {
            return;
        }
    }
    getNext().invoke(request, response);
}
Also used : AuthenticatedActionsHandler(org.keycloak.adapters.AuthenticatedActionsHandler) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment)

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