org.keycloak.adapters.spi.AuthChallenge Java Examples

The following examples show how to use org.keycloak.adapters.spi.AuthChallenge. 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: AbstractUndertowKeycloakAuthMech.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Call this inside your authenticate method.
 */
protected AuthenticationMechanismOutcome keycloakAuthenticate(HttpServerExchange exchange, SecurityContext securityContext, RequestAuthenticator authenticator) {
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        registerNotifications(securityContext);
        return AuthenticationMechanismOutcome.AUTHENTICATED;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge);
    }

    if (outcome == AuthOutcome.FAILED) {
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #2
Source File: AbstractKeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean authenticateInternal(Request request, HttpServletResponse response, Object loginConfig) throws IOException {
    CatalinaHttpFacade facade = new OIDCCatalinaHttpFacade(request, response);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        //needed for the EAP6/AS7 adapter relying on the tomcat core adapter
        facade.getResponse().sendError(401);
        return false;
    }
    AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);

    nodesRegistrationManagement.tryRegister(deployment);

    CatalinaRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        if (facade.isEnded()) {
            return false;
        }
        return true;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
    }
    return false;
}
 
Example #3
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected AuthChallenge challenge(final int code, final OIDCAuthenticationError.Reason reason, final String description) {
    return new AuthChallenge() {
        @Override
        public int getResponseCode() {
            return code;
        }

        @Override
        public boolean challenge(HttpFacade exchange) {
            OIDCAuthenticationError error = new OIDCAuthenticationError(reason, description);
            exchange.getRequest().setError(error);
            exchange.getResponse().sendError(code);
            return true;
        }
    };
}
 
Example #4
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected AuthChallenge checkStateCookie() {
    OIDCHttpFacade.Cookie stateCookie = getCookie(deployment.getStateCookieName());

    if (stateCookie == null) {
        log.warn("No state cookie");
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    // reset the cookie
    log.debug("** reseting application state cookie");
    facade.getResponse().resetCookie(deployment.getStateCookieName(), stateCookie.getPath());
    String stateCookieValue = getCookieValue(deployment.getStateCookieName());

    String state = getQueryParamValue(OAuth2Constants.STATE);
    if (state == null) {
        log.warn("state parameter was null");
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    if (!state.equals(stateCookieValue)) {
        log.warn("state parameter invalid");
        log.warn("cookie: " + stateCookieValue);
        log.warn("queryParam: " + state);
        return challenge(400, OIDCAuthenticationError.Reason.INVALID_STATE_COOKIE, null);
    }
    return null;

}
 
Example #5
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected AuthChallenge loginRedirect() {
    final String state = getStateCode();
    final String redirect =  getRedirectUri(state);
    if (redirect == null) {
        return challenge(403, OIDCAuthenticationError.Reason.NO_REDIRECT_URI, null);
    }
    return new AuthChallenge() {

        @Override
        public int getResponseCode() {
            return 0;
        }

        @Override
        public boolean challenge(HttpFacade exchange) {
            tokenStore.saveRequest();
            log.debug("Sending redirect to login page: " + redirect);
            exchange.getResponse().setStatus(302);
            exchange.getResponse().setCookie(deployment.getStateCookieName(), state, "/", null, -1, deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr()), true);
            exchange.getResponse().setHeader("Location", redirect);
            return true;
        }
    };
}
 
Example #6
Source File: AbstractSamlAuthMech.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
    AuthChallenge challenge = exchange.getAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY);
    if (challenge != null) {
        UndertowHttpFacade facade = createFacade(exchange);
        if (challenge.challenge(facade)) {
            return new ChallengeResult(true, exchange.getResponseCode());
        }
    }
    return new ChallengeResult(false);
}
 
Example #7
Source File: AbstractUndertowKeycloakAuthMech.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ChallengeResult sendChallenge(HttpServerExchange exchange, SecurityContext securityContext) {
    AuthChallenge challenge = exchange.getAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY);
    if (challenge != null) {
        UndertowHttpFacade facade = createFacade(exchange);
        if (challenge.challenge(facade)) {
            return new ChallengeResult(true, exchange.getResponseCode());
        }
    }
    return new ChallengeResult(false);
}
 
Example #8
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static AuthChallenge createAuthChallenge(final int httpError, final SamlAuthenticationError error) {
    return new AuthChallenge() {
        @Override
        public boolean challenge(HttpFacade exchange) {
            exchange.getRequest().setError(error);
            exchange.getResponse().sendError(httpError);
            return true;
        }

        @Override
        public int getResponseCode() {
            return httpError;
        }
    };
}
 
Example #9
Source File: BearerTokenRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AuthChallenge clientCertChallenge() {
    return new AuthChallenge() {
        @Override
        public int getResponseCode() {
            return 0;
        }

        @Override
        public boolean challenge(HttpFacade exchange) {
            // do the same thing as client cert auth
            return false;
        }
    };
}
 
Example #10
Source File: JaxrsBearerTokenFilterImpl.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void bearerAuthentication(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment) {
    BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(resolvedDeployment);
    AuthOutcome outcome = authenticator.authenticate(facade);
    
    if (outcome == AuthOutcome.NOT_ATTEMPTED && resolvedDeployment.isEnableBasicAuth()) {
        authenticator = new BasicAuthRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }
    
    if (outcome == AuthOutcome.FAILED || outcome == AuthOutcome.NOT_ATTEMPTED) {
        AuthChallenge challenge = authenticator.getChallenge();
        log.fine("Authentication outcome: " + outcome);
        boolean challengeSent = challenge.challenge(facade);
        if (!challengeSent) {
            // Use some default status code
            facade.getResponse().setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        }

        // Send response now (if not already sent)
        if (!facade.isResponseFinished()) {
            facade.getResponse().end();
        }
        return;
    } else {
        if (verifySslFailed(facade, resolvedDeployment)) {
            return;
        }
    }

    propagateSecurityContext(facade, request, resolvedDeployment, authenticator);
    handleAuthActions(facade, resolvedDeployment);
}
 
Example #11
Source File: HammockKeycloakJaxrsFilter.java    From hammock with Apache License 2.0 5 votes vote down vote up
private void bearerAuthentication(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment) {
    BearerTokenRequestAuthenticator authenticator = new BearerTokenRequestAuthenticator(resolvedDeployment);
    AuthOutcome outcome = authenticator.authenticate(facade);

    if (outcome == AuthOutcome.NOT_ATTEMPTED) {
        authenticator = new QueryParamterTokenRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }

    if (outcome == AuthOutcome.NOT_ATTEMPTED && resolvedDeployment.isEnableBasicAuth()) {
        authenticator = new BasicAuthRequestAuthenticator(resolvedDeployment);
        outcome = authenticator.authenticate(facade);
    }

    if (outcome == AuthOutcome.FAILED || outcome == AuthOutcome.NOT_ATTEMPTED) {
        AuthChallenge challenge = authenticator.getChallenge();
        boolean challengeSent = challenge.challenge(facade);
        if (!challengeSent) {
            // Use some default status code
            facade.getResponse().setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        }

        // Send response now (if not already sent)
        if (!facade.isResponseFinished()) {
            facade.getResponse().end();
        }
        return;
    } else {
        if (verifySslFailed(facade, resolvedDeployment)) {
            return;
        }
    }

    propagateSecurityContext(facade, request, resolvedDeployment, authenticator);
    handleAuthActions(facade, resolvedDeployment);
}
 
Example #12
Source File: KeycloakAuthFilter.java    From keycloak-dropwizard-integration with Apache License 2.0 5 votes vote down vote up
public void validateRequest(final ContainerRequestContext requestContext) {
    if (requestContext.getSecurityContext().getUserPrincipal() != null) {
        // the user is already authenticated, further processing is not necessary
        return;
    }
    Request request = Request.getBaseRequest((ServletRequest)
            requestContext.getProperty(HttpServletRequest.class.getName()));
    JaxrsHttpFacade facade = new JaxrsHttpFacade(requestContext, requestContext.getSecurityContext());
    request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);

    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        return;
    }

    AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);

    tokenStore.checkCurrentToken();
    JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        return;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
        if (!adapterConfig.isBearerOnly()) {
            // create session and set cookie for client
            facade.getResponse().setCookie("JSESSIONID", request.getSession().getId(), "/", null, -1, false, false);
        }
        facade.getResponse().end();
    }
}
 
Example #13
Source File: AlfrescoBearerTokenRequestAuthenticator.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected AuthChallenge challengeResponse(HttpFacade facade, Reason reason, String error, String description)
{
    this.validationFailureDescription = description;
    
    return super.challengeResponse(facade, reason, error, description);
}
 
Example #14
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private static AuthChallenge createAuthChallenge403(final StatusResponseType responseType) {
    return createAuthChallenge(403, new SamlAuthenticationError(SamlAuthenticationError.Reason.ERROR_STATUS, responseType));
}
 
Example #15
Source File: SamlAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthChallenge getChallenge() {
    return this.handler.getChallenge();
}
 
Example #16
Source File: ElytronHttpFacade.java    From keycloak with Apache License 2.0 4 votes vote down vote up
void noAuthenticationInProgress(AuthChallenge challenge) {
    if (challenge != null) {
        challenge.challenge(this);
    }
    this.request.noAuthenticationInProgress(response -> responseConsumer.accept(response));
}
 
Example #17
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private AuthOutcome failed(AuthChallenge challenge) {
    this.challenge = challenge;
    return AuthOutcome.FAILED;
}
 
Example #18
Source File: AbstractSamlAuthenticationHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public AuthChallenge getChallenge() {
    return this.challenge;
}
 
Example #19
Source File: AbstractSamlAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (log.isTraceEnabled()) {
        log.trace("*** authenticate");
    }
    Request request = resolveRequest(req);
    JettyHttpFacade facade = new JettyHttpFacade(request, (HttpServletResponse) res);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        log.debug("*** deployment isn't configured return false");
        return Authentication.UNAUTHENTICATED;
    }
    boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml");
    if (!mandatory && !isEndpoint)
        return new DeferredAuthentication(this);
    JettySamlSessionStore tokenStore = getTokenStore(request, facade, deployment);

    SamlAuthenticator authenticator = null;
    if (isEndpoint) {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new SamlEndpoint(facade, deployment, sessionStore);
            }
        };

    } else {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new BrowserHandler(facade, deployment, sessionStore);
            }
        };
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        if (facade.isEnded()) {
            return Authentication.SEND_SUCCESS;
        }
        SamlSession samlSession = tokenStore.getAccount();
        Authentication authentication = register(request, samlSession);
        return authentication;

    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
        logoutCurrent(request);
        if (deployment.getLogoutPage() != null) {
            forwardToLogoutPage(request, (HttpServletResponse)res, deployment);

        }
        return Authentication.SEND_CONTINUE;
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
    }
    return Authentication.SEND_CONTINUE;
}
 
Example #20
Source File: AbstractSamlAuthMech.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Call this inside your authenticate method.
 */
public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) {
    UndertowHttpFacade facade = createFacade(exchange);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (!deployment.isConfigured()) {
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    SamlSessionStore sessionStore = getTokenStore(exchange, facade, deployment, securityContext);
    SamlAuthenticator authenticator = null;
    if (exchange.getRequestPath().endsWith("/saml")) {
        authenticator = new UndertowSamlEndpoint(facade, deploymentContext.resolveDeployment(facade), sessionStore);
    } else {
        authenticator = new UndertowSamlAuthenticator(securityContext, facade, deploymentContext.resolveDeployment(facade), sessionStore);

    }

    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        registerNotifications(securityContext);
        return AuthenticationMechanismOutcome.AUTHENTICATED;
    }
    if (outcome == AuthOutcome.NOT_AUTHENTICATED) {
        // we are in passive mode and user is not authenticated, let app server to try another auth mechanism
        // See KEYCLOAK-2107, AbstractSamlAuthenticationHandler
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
        securityContext.logout();
        if (deployment.getLogoutPage() != null) {
            redirectLogout(deployment, exchange);
        }
        return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, challenge);
        if (authenticator instanceof UndertowSamlEndpoint) {
            exchange.getSecurityContext().setAuthenticationRequired();
        }
    }

    if (outcome == AuthOutcome.FAILED) {
        return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
    }
    return AuthenticationMechanismOutcome.NOT_ATTEMPTED;
}
 
Example #21
Source File: KeycloakHttpServerAuthenticationMechanism.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
    LOGGER.debugf("Evaluating request for path [%s]", request.getRequestURI());
    SamlDeploymentContext 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, getSessionIdMapper(request), getSessionIdMapperUpdater(request), deploymentContext, callbackHandler);
    SamlDeployment deployment = httpFacade.getDeployment();

    if (!deployment.isConfigured()) {
        request.noAuthenticationInProgress();
        return;
    }

    if (deployment.getLogoutPage() != null && httpFacade.getRequest().getRelativePath().contains(deployment.getLogoutPage())) {
        LOGGER.debugf("Ignoring request for [%s] and logout page [%s].", request.getRequestURI(), deployment.getLogoutPage());
        httpFacade.authenticationCompleteAnonymous();
        return;
    }

    SamlAuthenticator authenticator;

    if (httpFacade.getRequest().getRelativePath().endsWith("/saml")) {
        authenticator = new ElytronSamlEndpoint(httpFacade, deployment);
    } else {
        authenticator = new ElytronSamlAuthenticator(httpFacade, deployment, callbackHandler);

    }

    AuthOutcome outcome = authenticator.authenticate();

    if (outcome == AuthOutcome.AUTHENTICATED) {
        httpFacade.authenticationComplete();
        return;
    }

    if (outcome == AuthOutcome.NOT_AUTHENTICATED) {
        httpFacade.noAuthenticationInProgress(null);
        return;
    }

    if (outcome == AuthOutcome.LOGGED_OUT) {
        if (deployment.getLogoutPage() != null) {
            redirectLogout(deployment, httpFacade);
        }
        httpFacade.authenticationInProgress();
        return;
    }

    AuthChallenge challenge = authenticator.getChallenge();

    if (challenge != null) {
        httpFacade.noAuthenticationInProgress(challenge);
        return;
    }

    if (outcome == AuthOutcome.FAILED) {
        httpFacade.authenticationFailed();
        return;
    }

    httpFacade.authenticationInProgress();
}
 
Example #22
Source File: SamlFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    ServletHttpFacade facade = new ServletHttpFacade(request, response);
    SamlDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        response.sendError(403);
        log.fine("deployment not configured");
        return;
    }
    FilterSamlSessionStore tokenStore = new FilterSamlSessionStore(request, facade, 100000, idMapper, deployment);
    boolean isEndpoint = request.getRequestURI().substring(request.getContextPath().length()).endsWith("/saml");
    SamlAuthenticator authenticator;
    if (isEndpoint) {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new SamlEndpoint(facade, deployment, sessionStore);
            }
        };

    } else {
        authenticator = new SamlAuthenticator(facade, deployment, tokenStore) {
            @Override
            protected void completeAuthentication(SamlSession account) {

            }

            @Override
            protected SamlAuthenticationHandler createBrowserHandler(HttpFacade facade, SamlDeployment deployment, SamlSessionStore sessionStore) {
                return new BrowserHandler(facade, deployment, sessionStore);
            }
        };
    }
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        log.fine("AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        HttpServletRequestWrapper wrapper = tokenStore.getWrap();
        chain.doFilter(wrapper, res);
        return;
    }
    if (outcome == AuthOutcome.LOGGED_OUT) {
        tokenStore.logoutAccount();
        String logoutPage = deployment.getLogoutPage();
        if (logoutPage != null) {
            if (PROTOCOL_PATTERN.matcher(logoutPage).find()) {
                response.sendRedirect(logoutPage);
                log.log(Level.FINE, "Redirected to logout page {0}", logoutPage);
            } else {
                RequestDispatcher disp = req.getRequestDispatcher(logoutPage);
                disp.forward(req, res);
            }
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        log.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    if (deployment.isIsPassive() && outcome == AuthOutcome.NOT_AUTHENTICATED) {
        log.fine("PASSIVE_NOT_AUTHENTICATED");
        if (facade.isEnded()) {
            return;
        }
        chain.doFilter(req, res);
        return;
    }

    if (!facade.isEnded()) {
        response.sendError(403);
    }

}
 
Example #23
Source File: KeycloakHttpServerAuthenticationMechanism.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example #24
Source File: ElytronHttpFacade.java    From keycloak with Apache License 2.0 4 votes vote down vote up
void noAuthenticationInProgress(AuthChallenge challenge) {
    if (challenge != null) {
        challenge.challenge(this);
    }
    this.request.noAuthenticationInProgress(response -> responseConsumer.accept(response));
}
 
Example #25
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (log.isTraceEnabled()) {
        log.trace("*** authenticate");
    }
    Request request = resolveRequest(req);
    OIDCJettyHttpFacade facade = new OIDCJettyHttpFacade(request, (HttpServletResponse) res);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
    if (deployment == null || !deployment.isConfigured()) {
        log.debug("*** deployment isn't configured return false");
        return Authentication.UNAUTHENTICATED;
    }
    PreAuthActionsHandler handler = new PreAuthActionsHandler(createSessionManagement(request), deploymentContext, facade);
    if (handler.handleRequest()) {
        return Authentication.SEND_SUCCESS;
    }
    if (!mandatory)
        return new DeferredAuthentication(this);
    AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
    nodesRegistrationManagement.tryRegister(deployment);

    tokenStore.checkCurrentToken();
    JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();
    if (outcome == AuthOutcome.AUTHENTICATED) {
        if (facade.isEnded()) {
            return Authentication.SEND_SUCCESS;
        }

        Authentication authentication = register(request, authenticator.principal);
        AuthenticatedActionsHandler authenticatedActionsHandler = new AuthenticatedActionsHandler(deployment, facade);
        if (authenticatedActionsHandler.handledRequest()) {
            return Authentication.SEND_SUCCESS;
        }
        return authentication;

    }
    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        challenge.challenge(facade);
    }
    return Authentication.SEND_CONTINUE;
}
 
Example #26
Source File: RequestAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthChallenge getChallenge() {
    return challenge;
}
 
Example #27
Source File: OAuthRequestAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthChallenge getChallenge() {
    return challenge;
}
 
Example #28
Source File: BearerTokenRequestAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AuthChallenge getChallenge() {
    return challenge;
}
 
Example #29
Source File: UndertowKeycloakConsumer.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange httpExchange) throws Exception {
    if (shouldSkip(httpExchange.getRequestPath())) {
        super.handleRequest(httpExchange);
        return;
    }

    //perform only non-blocking operation on exchange
    if (httpExchange.isInIoThread()) {
        httpExchange.dispatch(this);
        return;
    }

    OIDCUndertowHttpFacade facade = new OIDCUndertowHttpFacade(httpExchange);
    KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);

    if (deployment == null || !deployment.isConfigured()) {
        httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
        LOG.fine("deployment not configured");
        return;
    }

    LOG.fine("executing PreAuthActionsHandler");
    SessionManagementBridge bridge = new SessionManagementBridge(userSessionManagement, sessionManager);
    PreAuthActionsHandler preAuth = new PreAuthActionsHandler(bridge, deploymentContext, facade);
    if (preAuth.handleRequest()) return;

    SecurityContext securityContext = httpExchange.getSecurityContext();
    if (securityContext == null) {
        securityContext = new SecurityContextImpl(httpExchange, IDENTITY_MANAGER);
    }
    AdapterTokenStore tokenStore = getTokenStore(httpExchange, facade, deployment, securityContext);
    tokenStore.checkCurrentToken();

    LOG.fine("executing AuthenticatedActionsHandler");
    RequestAuthenticator authenticator = new UndertowRequestAuthenticator(facade, deployment, confidentialPort, securityContext, httpExchange, tokenStore);
    AuthOutcome outcome = authenticator.authenticate();

    if (outcome == AuthOutcome.AUTHENTICATED) {
        LOG.fine("AUTHENTICATED");
        if (httpExchange.isResponseComplete()) {
            return;
        }
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, facade);
        if (actions.handledRequest()) {
            return;
        } else {
            final Account authenticatedAccount = securityContext.getAuthenticatedAccount();
            if (authenticatedAccount instanceof KeycloakUndertowAccount) {
                final KeycloakUndertowAccount kua = (KeycloakUndertowAccount) authenticatedAccount;
                httpExchange.putAttachment(KEYCLOAK_PRINCIPAL_KEY, (KeycloakPrincipal) kua.getPrincipal());
            }

            Set<String> roles = Optional
              .ofNullable(authenticatedAccount.getRoles())
              .orElse((Set<String>) Collections.EMPTY_SET);

            LOG.log(Level.FINE, "Allowed roles: {0}, current roles: {1}", new Object[] {allowedRoles, roles});

            if (isRoleAllowed(roles, httpExchange)) {
                super.handleRequest(httpExchange);
            } else {
                httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
            }

            return;
        }
    }

    AuthChallenge challenge = authenticator.getChallenge();
    if (challenge != null) {
        LOG.fine("challenge");
        challenge.challenge(facade);
        return;
    }

    httpExchange.setStatusCode(StatusCodes.FORBIDDEN);
}
 
Example #30
Source File: KeycloakOIDCFilter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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 UserSessionManagement() {
        @Override
        public void logoutAll() {
            if (idMapper != null) {
                idMapper.clear();
            }
        }

        @Override
        public void logoutHttpSessions(List<String> ids) {
            log.fine("**************** logoutHttpSessions");
            //System.err.println("**************** logoutHttpSessions");
            for (String id : ids) {
                log.finest("removed idMapper: " + id);
                idMapper.removeSession(id);
            }

        }
    }, 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);

}