Search in sources :

Example 1 with AuthChallenge

use of org.keycloak.adapters.spi.AuthChallenge in project keycloak by keycloak.

the class AbstractKeycloakJettyAuthenticator method validateRequest.

@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;
}
Also used : AuthenticatedActionsHandler(org.keycloak.adapters.AuthenticatedActionsHandler) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) Request(org.eclipse.jetty.server.Request) ServletRequest(javax.servlet.ServletRequest) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) AuthOutcome(org.keycloak.adapters.spi.AuthOutcome) PreAuthActionsHandler(org.keycloak.adapters.PreAuthActionsHandler) AdapterTokenStore(org.keycloak.adapters.AdapterTokenStore)

Example 2 with AuthChallenge

use of org.keycloak.adapters.spi.AuthChallenge in project keycloak by keycloak.

the class AbstractUndertowKeycloakAuthMech method keycloakAuthenticate.

/**
 * 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;
}
Also used : AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) AuthOutcome(org.keycloak.adapters.spi.AuthOutcome)

Example 3 with AuthChallenge

use of org.keycloak.adapters.spi.AuthChallenge 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 4 with AuthChallenge

use of org.keycloak.adapters.spi.AuthChallenge in project keycloak by keycloak.

the class KeycloakAuthenticationProcessingFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    log.debug("Attempting Keycloak authentication");
    HttpFacade facade = new SimpleHttpFacade(request, response);
    KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade);
    // using Spring authenticationFailureHandler
    deployment.setDelegateBearerErrorResponseSending(true);
    AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response);
    RequestAuthenticator authenticator = requestAuthenticatorFactory.createRequestAuthenticator(facade, request, deployment, tokenStore, -1);
    AuthOutcome result = authenticator.authenticate();
    log.debug("Auth outcome: {}", result);
    if (AuthOutcome.FAILED.equals(result)) {
        AuthChallenge challenge = authenticator.getChallenge();
        if (challenge != null) {
            challenge.challenge(facade);
        }
        throw new KeycloakAuthenticationException("Invalid authorization header, see WWW-Authenticate header for details");
    }
    if (AuthOutcome.NOT_ATTEMPTED.equals(result)) {
        AuthChallenge challenge = authenticator.getChallenge();
        if (challenge != null) {
            challenge.challenge(facade);
        }
        if (deployment.isBearerOnly()) {
            // no redirection in this mode, throwing exception for the spring handler
            throw new KeycloakAuthenticationException("Authorization header not found,  see WWW-Authenticate header");
        } else {
            // let continue if challenged, it may redirect
            return null;
        }
    } else if (AuthOutcome.AUTHENTICATED.equals(result)) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Assert.notNull(authentication, "Authentication SecurityContextHolder was null");
        return authenticationManager.authenticate(authentication);
    } else {
        AuthChallenge challenge = authenticator.getChallenge();
        if (challenge != null) {
            challenge.challenge(facade);
        }
        return null;
    }
}
Also used : AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) RequestAuthenticator(org.keycloak.adapters.RequestAuthenticator) SimpleHttpFacade(org.keycloak.adapters.springsecurity.facade.SimpleHttpFacade) HttpFacade(org.keycloak.adapters.spi.HttpFacade) Authentication(org.springframework.security.core.Authentication) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) SimpleHttpFacade(org.keycloak.adapters.springsecurity.facade.SimpleHttpFacade) AuthOutcome(org.keycloak.adapters.spi.AuthOutcome) KeycloakAuthenticationException(org.keycloak.adapters.springsecurity.KeycloakAuthenticationException) AdapterTokenStore(org.keycloak.adapters.AdapterTokenStore)

Example 5 with AuthChallenge

use of org.keycloak.adapters.spi.AuthChallenge in project keycloak by keycloak.

the class OAuthRequestAuthenticator method resolveCode.

/**
 * Start or continue the oauth login process.
 * <p/>
 * if code query parameter is not present, then browser is redirected to authUrl.  The redirect URL will be
 * the URL of the current request.
 * <p/>
 * If code query parameter is present, then an access token is obtained by invoking a secure request to the codeUrl.
 * If the access token is obtained, the browser is again redirected to the current request URL, but any OAuth
 * protocol specific query parameters are removed.
 *
 * @return null if an access token was obtained, otherwise a challenge is returned
 */
protected AuthChallenge resolveCode(String code) {
    // abort if not HTTPS
    if (!isRequestSecure() && deployment.getSslRequired().isRequired(facade.getRequest().getRemoteAddr())) {
        log.error("Adapter requires SSL. Request: " + facade.getRequest().getURI());
        return challenge(403, OIDCAuthenticationError.Reason.SSL_REQUIRED, null);
    }
    log.debug("checking state cookie for after code");
    AuthChallenge challenge = checkStateCookie();
    if (challenge != null)
        return challenge;
    AccessTokenResponse tokenResponse = null;
    strippedOauthParametersRequestUri = rewrittenRedirectUri(stripOauthParametersFromRedirect());
    try {
        // For COOKIE store we don't have httpSessionId and single sign-out won't be available
        String httpSessionId = deployment.getTokenStore() == TokenStore.SESSION ? reqAuthenticator.changeHttpSessionId(true) : null;
        tokenResponse = ServerRequest.invokeAccessCodeToToken(deployment, code, strippedOauthParametersRequestUri, httpSessionId);
    } catch (ServerRequest.HttpFailure failure) {
        log.error("failed to turn code into token");
        log.error("status from server: " + failure.getStatus());
        if (failure.getError() != null && !failure.getError().trim().isEmpty()) {
            log.error("   " + failure.getError());
        }
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    } catch (IOException e) {
        log.error("failed to turn code into token", e);
        return challenge(403, OIDCAuthenticationError.Reason.CODE_TO_TOKEN_FAILURE, null);
    }
    tokenString = tokenResponse.getToken();
    refreshToken = tokenResponse.getRefreshToken();
    idTokenString = tokenResponse.getIdToken();
    log.debug("Verifying tokens");
    if (log.isTraceEnabled()) {
        logToken("\taccess_token", tokenString);
        logToken("\tid_token", idTokenString);
        logToken("\trefresh_token", refreshToken);
    }
    try {
        AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, idTokenString, deployment);
        token = tokens.getAccessToken();
        idToken = tokens.getIdToken();
        log.debug("Token Verification succeeded!");
    } catch (VerificationException e) {
        log.error("failed verification of token: " + e.getMessage());
        return challenge(403, OIDCAuthenticationError.Reason.INVALID_TOKEN, null);
    }
    if (tokenResponse.getNotBeforePolicy() > deployment.getNotBefore()) {
        deployment.updateNotBefore(tokenResponse.getNotBeforePolicy());
    }
    if (token.getIssuedAt() < deployment.getNotBefore()) {
        log.error("Stale token");
        return challenge(403, OIDCAuthenticationError.Reason.STALE_TOKEN, null);
    }
    log.debug("successful authenticated");
    return null;
}
Also used : AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) AuthChallenge(org.keycloak.adapters.spi.AuthChallenge) VerificationException(org.keycloak.common.VerificationException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Aggregations

AuthChallenge (org.keycloak.adapters.spi.AuthChallenge)13 AuthOutcome (org.keycloak.adapters.spi.AuthOutcome)12 KeycloakDeployment (org.keycloak.adapters.KeycloakDeployment)6 AdapterTokenStore (org.keycloak.adapters.AdapterTokenStore)4 AuthenticatedActionsHandler (org.keycloak.adapters.AuthenticatedActionsHandler)4 SamlAuthenticator (org.keycloak.adapters.saml.SamlAuthenticator)4 SamlDeployment (org.keycloak.adapters.saml.SamlDeployment)4 PreAuthActionsHandler (org.keycloak.adapters.PreAuthActionsHandler)3 RequestAuthenticator (org.keycloak.adapters.RequestAuthenticator)3 SamlSessionStore (org.keycloak.adapters.saml.SamlSessionStore)3 HttpFacade (org.keycloak.adapters.spi.HttpFacade)3 ServletRequest (javax.servlet.ServletRequest)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 UserAuthentication (org.eclipse.jetty.security.UserAuthentication)2 DeferredAuthentication (org.eclipse.jetty.security.authentication.DeferredAuthentication)2 Authentication (org.eclipse.jetty.server.Authentication)2 Request (org.eclipse.jetty.server.Request)2 SamlSession (org.keycloak.adapters.saml.SamlSession)2