Search in sources :

Example 31 with KeycloakDeployment

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

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

the class AdapterDeploymentContextFactoryBean method afterPropertiesSet.

@Override
public void afterPropertiesSet() throws Exception {
    if (keycloakConfigResolver != null) {
        adapterDeploymentContext = new AdapterDeploymentContext(keycloakConfigResolver);
    } else {
        log.info("Loading Keycloak deployment from configuration file: {}", keycloakConfigFileResource);
        KeycloakDeployment deployment = loadKeycloakDeployment();
        adapterDeploymentContext = new AdapterDeploymentContext(deployment);
    }
}
Also used : AdapterDeploymentContext(org.keycloak.adapters.AdapterDeploymentContext) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment)

Example 33 with KeycloakDeployment

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

the class KeycloakIdentityProvider method init.

@Override
public void init(Container container) {
    if (httpClient != null) {
        return;
    }
    sessionMaxSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_MAX_MINUTES, IDENTITY_SESSION_MAX_MINUTES_DEFAULT) * 60;
    if (sessionMaxSeconds < 60) {
        throw new IllegalArgumentException(IDENTITY_SESSION_MAX_MINUTES + " must be more than 1 minute");
    }
    // Use the same, as a session is never idle because we periodically check if the refresh token is
    // still good in frontend code, this check will reset the idle timeout anyway
    sessionTimeoutSeconds = sessionMaxSeconds;
    sessionOfflineTimeoutSeconds = getInteger(container.getConfig(), IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES, IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES_DEFAULT) * 60;
    if (sessionOfflineTimeoutSeconds < 60) {
        throw new IllegalArgumentException(IDENTITY_SESSION_OFFLINE_TIMEOUT_MINUTES + " must be more than 1 minute");
    }
    keycloakServiceUri = UriBuilder.fromPath("/").scheme("http").host(getString(container.getConfig(), KEYCLOAK_HOST, KEYCLOAK_HOST_DEFAULT)).port(getInteger(container.getConfig(), KEYCLOAK_PORT, KEYCLOAK_PORT_DEFAULT)).path(KEYCLOAK_AUTH_PATH);
    LOG.info("Keycloak service URL: " + keycloakServiceUri.build());
    ResteasyClientBuilder clientBuilder = new ResteasyClientBuilder().connectTimeout(getInteger(container.getConfig(), KEYCLOAK_CONNECT_TIMEOUT, KEYCLOAK_CONNECT_TIMEOUT_DEFAULT), TimeUnit.MILLISECONDS).readTimeout(getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT), TimeUnit.MILLISECONDS).connectionPoolSize(getInteger(container.getConfig(), KEYCLOAK_CLIENT_POOL_SIZE, KEYCLOAK_CLIENT_POOL_SIZE_DEFAULT));
    httpClient = WebClient.registerDefaults(clientBuilder).build();
    setActiveCredentials(getDefaultKeycloakGrant(container));
    keycloakDeploymentCache = createKeycloakDeploymentCache();
    keycloakConfigResolver = request -> {
        // The realm we authenticate against must be available as a request header
        String realm = request.getHeader(REALM_PARAM_NAME);
        if (realm == null || realm.length() == 0) {
            LOG.finer("No realm in request, no authentication will be attempted: " + request.getURI());
            return notAuthenticatedKeycloakDeployment;
        }
        KeycloakDeployment keycloakDeployment = getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID);
        if (keycloakDeployment == null) {
            LOG.fine("No Keycloak deployment available for realm, no authentication will be attempted: " + request.getURI());
            return notAuthenticatedKeycloakDeployment;
        }
        return keycloakDeployment;
    };
    if (container.isDevMode()) {
        authProxyHandler = ProxyHandler.builder().setProxyClient(new LoadBalancingProxyClient().addHost(keycloakServiceUri.clone().replacePath("").build())).setMaxRequestTime(getInteger(container.getConfig(), KEYCLOAK_REQUEST_TIMEOUT, KEYCLOAK_REQUEST_TIMEOUT_DEFAULT)).setNext(ResponseCodeHandler.HANDLE_404).setReuseXForwarded(true).build();
    }
    // TODO Not a great way to block startup while we wait for other services (Hystrix?)
    waitForKeycloak();
    LOG.info("Keycloak identity provider available: " + keycloakServiceUri.build());
}
Also used : ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) LoadBalancingProxyClient(io.undertow.server.handlers.proxy.LoadBalancingProxyClient)

Example 34 with KeycloakDeployment

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

the class KeycloakIdentityProvider method createKeycloakDeploymentCache.

protected LoadingCache<KeycloakRealmClient, KeycloakDeployment> createKeycloakDeploymentCache() {
    CacheLoader<KeycloakRealmClient, KeycloakDeployment> loader = new CacheLoader<KeycloakRealmClient, KeycloakDeployment>() {

        public KeycloakDeployment load(KeycloakRealmClient keycloakRealmClient) {
            LOG.fine("Loading adapter config for client '" + keycloakRealmClient.clientId + "' in realm '" + keycloakRealmClient.realm + "'");
            // KeycloakResource keycloak = getKeycloak();
            KeycloakResource keycloak = getTarget(httpClient, keycloakServiceUri.build(), null, null, null).proxy(KeycloakResource.class);
            // Can't get adapter for client in another realm
            AdapterConfig adapterConfig = keycloak.getAdapterConfig(// keycloakRealmClient.clientId
            keycloakRealmClient.realm, // keycloakRealmClient.clientId
            KEYCLOAK_CLIENT_ID);
            // The auth-server-url in the adapter config must be reachable by this manager it will be the frontend URL by default
            adapterConfig.setAuthServerUrl(keycloakServiceUri.clone().build().toString());
            return KeycloakDeploymentBuilder.build(adapterConfig);
        }
    };
    // TODO configurable? Or replace all of this with Observable.cache()?
    return CacheBuilder.newBuilder().maximumSize(500).expireAfterWrite(10, MINUTES).build(loader);
}
Also used : KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) AdapterConfig(org.keycloak.representations.adapters.config.AdapterConfig) CacheLoader(com.google.common.cache.CacheLoader)

Example 35 with KeycloakDeployment

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

the class KeycloakAdapterPolicyEnforcer method requestAuthorizationToken.

private AccessToken requestAuthorizationToken(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) {
    if (getEnforcerConfig().getUserManagedAccess() != null) {
        return null;
    }
    try {
        KeycloakSecurityContext securityContext = httpFacade.getSecurityContext();
        String accessTokenString = securityContext.getTokenString();
        KeycloakDeployment deployment = getPolicyEnforcer().getDeployment();
        AccessToken accessToken = securityContext.getToken();
        AuthorizationRequest authzRequest = new AuthorizationRequest();
        if (isBearerAuthorization(httpFacade) || accessToken.getAuthorization() != null) {
            authzRequest.addPermission(pathConfig.getId(), methodConfig.getScopes());
        }
        if (!claims.isEmpty()) {
            authzRequest.setClaimTokenFormat("urn:ietf:params:oauth:token-type:jwt");
            authzRequest.setClaimToken(Base64.encodeBytes(JsonSerialization.writeValueAsBytes(claims)));
        }
        if (accessToken.getAuthorization() != null) {
            authzRequest.setRpt(accessTokenString);
        }
        LOGGER.debug("Obtaining authorization for authenticated user.");
        AuthorizationResponse authzResponse;
        if (isBearerAuthorization(httpFacade)) {
            authzRequest.setSubjectToken(accessTokenString);
            authzResponse = getAuthzClient().authorization().authorize(authzRequest);
        } else {
            authzResponse = getAuthzClient().authorization(accessTokenString).authorize(authzRequest);
        }
        if (authzResponse != null) {
            return AdapterTokenVerifier.verifyToken(authzResponse.getToken(), deployment);
        }
    } catch (AuthorizationDeniedException ignore) {
        LOGGER.debug("Authorization denied", ignore);
    } catch (Exception e) {
        LOGGER.debug("Authorization failed", e);
    }
    return null;
}
Also used : AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) KeycloakSecurityContext(org.keycloak.KeycloakSecurityContext) AccessToken(org.keycloak.representations.AccessToken) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse)

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