Java Code Examples for org.keycloak.adapters.KeycloakDeploymentBuilder#build()

The following examples show how to use org.keycloak.adapters.KeycloakDeploymentBuilder#build() . 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: KcinitDriver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void logout() throws Exception {
    String token = readRefreshToken(getMasterClient());
    if (token != null) {
        try {
            KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getConfig());
            ServerRequest.invokeLogout(deployment, token);
        } catch (Exception e) {
            if (debug) {
                e.printStackTrace();
            }
        }

    }
    if (getTokenDirectory().exists()) {
        for (File fp : getTokenDirectory().listFiles()) fp.delete();
    }
}
 
Example 2
Source File: PathBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    String path = request.getURI();
    int multitenantIndex = path.indexOf("multitenant/");
    if (multitenantIndex == -1) {
        throw new IllegalStateException("Not able to resolve realm from the request path!");
    }

    String realm = path.substring(path.indexOf("multitenant/")).split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }

    KeycloakDeployment deployment = cache.get(realm);
    if (null == deployment) {
        // not found on the simple cache, try to load it from the file system
        InputStream is = getClass().getResourceAsStream("/" + realm + "-keycloak.json");
        if (is == null) {
            throw new IllegalStateException("Not able to find the file /" + realm + "-keycloak.json");
        }
        deployment = KeycloakDeploymentBuilder.build(is);
        cache.put(realm, deployment);
    }

    return deployment;
}
 
Example 3
Source File: BundleBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected KeycloakDeployment findDeployment(HttpFacade.Request request) {
    if (bundleContext == null) {
        throw new IllegalStateException("bundleContext must be set for BundleBasedKeycloakConfigResolver!");
    }

    URL url = bundleContext.getBundle().getResource(configLocation);
    if (url == null) {
        throw new IllegalStateException("Failed to find the file " + configLocation + " on classpath.");
    }

    try {
        InputStream is = url.openStream();
        return KeycloakDeploymentBuilder.build(is);
    } catch (IOException ioe) {
        throw new IllegalStateException("Error reading file' " + configLocation + "' from bundle classpath.", ioe);
    }
}
 
Example 4
Source File: AbstractKeycloakLoginModule.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected KeycloakDeployment resolveDeployment(String keycloakConfigFile) {
    try {
        InputStream is = null;
        if (keycloakConfigFile.startsWith(PROFILE_RESOURCE)) {
            try {
                is = new URL(keycloakConfigFile).openStream();
            } catch (MalformedURLException mfue) {
                throw new RuntimeException(mfue);
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        } else {
            is = FindFile.findFile(keycloakConfigFile);
        }
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is);
        return kd;

    } catch (RuntimeException e) {
        getLogger().debug("Unable to find or parse file " + keycloakConfigFile + " due to " + e.getMessage(), e);
        throw e;
    }
}
 
Example 5
Source File: AtlasSecurityConfig.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Bean
protected AdapterDeploymentContext adapterDeploymentContext() throws Exception {
    AdapterDeploymentContextFactoryBean factoryBean;
    String fileName = configuration.getString("atlas.authentication.method.keycloak.file");
    if (fileName != null && !fileName.isEmpty()) {
        keycloakConfigFileResource = new FileSystemResource(fileName);
        factoryBean = new AdapterDeploymentContextFactoryBean(keycloakConfigFileResource);
    } else {
        Configuration conf = configuration.subset("atlas.authentication.method.keycloak");
        AdapterConfig cfg = new AdapterConfig();
        cfg.setRealm(conf.getString("realm", "atlas.com"));
        cfg.setAuthServerUrl(conf.getString("auth-server-url", "https://localhost/auth"));
        cfg.setResource(conf.getString("resource", "none"));

        Map<String,Object> credentials = new HashMap<>();
        credentials.put("secret", conf.getString("credentials-secret", "nosecret"));
        cfg.setCredentials(credentials);
        KeycloakDeployment dep = KeycloakDeploymentBuilder.build(cfg);
        factoryBean = new AdapterDeploymentContextFactoryBean(new KeycloakConfigResolver() {
            @Override
            public KeycloakDeployment resolve(HttpFacade.Request request) {
                return dep;
            }
        });
    }

    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}
 
Example 6
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolvingClaimsOnce() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only-with-cip.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();

    OIDCHttpFacade httpFacade = createHttpFacade("/api/resourcea", token, new Function<String, String>() {
        AtomicBoolean resolved = new AtomicBoolean();

        @Override
        public String apply(String s) {
            Assert.assertTrue(resolved.compareAndSet(false, true));
            return "value-" + s;
        }
    });

    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    Permission permission = context.getPermissions().get(0);
    Map<String, Set<String>> claims = permission.getClaims();

    assertTrue(context.isGranted());
    assertEquals("value-claim-a", claims.get("claim-a").iterator().next());
    assertEquals("claim-b", claims.get("claim-b").iterator().next());
}
 
Example 7
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testBearerOnlyClientResponse() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/resourcea");
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);

    assertFalse(context.isGranted());
    assertEquals(403, TestResponse.class.cast(httpFacade.getResponse()).getStatus());

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();

    httpFacade = createHttpFacade("/api/resourcea", token);

    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());

    httpFacade = createHttpFacade("/api/resourceb");

    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    assertEquals(403, TestResponse.class.cast(httpFacade.getResponse()).getStatus());
}
 
Example 8
Source File: DolphinKeycloakConfigResolver.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
public KeycloakDeployment resolve(final HttpFacade.Request request) {
    Assert.requireNonNull(request, "request");

    final String realmName = Optional.ofNullable(request.getHeader(REALM_NAME_HEADER)).
            orElse(configuration.getRealmName());
    final String applicationName = Optional.ofNullable(request.getHeader(APPLICATION_NAME_HEADER)).
            orElse(configuration.getApplicationName());
    final String authEndPoint = configuration.getAuthEndpoint();
    final boolean cors = configuration.isCors();

    Optional.ofNullable(realmName).orElseThrow(() -> new SecurityException("Realm name for security check is not configured!"));
    Optional.ofNullable(applicationName).orElseThrow(() -> new SecurityException("Application name for security check is not configured!"));
    Optional.ofNullable(authEndPoint).orElseThrow(() -> new SecurityException("Auth endpoint for security check is not configured!"));

    LOG.debug("Defined Keycloak AdapterConfig for request against realm '" +realmName + "' and app '" + applicationName + "'");

    final AdapterConfig adapterConfig = new AdapterConfig();
    LOG.debug("Checking if realm '" +realmName + "' is allowed");
    if(isRealmAllowed(realmName)){
        adapterConfig.setRealm(realmName);
    }else{
        if(LOG.isDebugEnabled()) {
            final String allowedRealms = configuration.getRealmNames().stream().reduce("", (a, b) -> a + "," + b);
            LOG.debug("Realm '" + realmName + "' is not allowed! Allowed realms are {}", allowedRealms);
        }
        throw new SecurityException("Access Denied! The given realm is not in the allowed realms.");
    }

    adapterConfig.setResource(applicationName);
    adapterConfig.setAuthServerUrl(authEndPoint);
    adapterConfig.setCors(cors);

    Optional.ofNullable(request.getHeader(BEARER_ONLY_HEADER)).
            ifPresent(v -> adapterConfig.setBearerOnly(true));

    return KeycloakDeploymentBuilder.build(adapterConfig);
}
 
Example 9
Source File: KeycloakOIDCFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakDeployment createKeycloakDeploymentFrom(InputStream is) {
    if (is == null) {
        log.fine("No adapter configuration. Keycloak is unconfigured and will deny all requests.");
        return new KeycloakDeployment();
    }
    return KeycloakDeploymentBuilder.build(is);
}
 
Example 10
Source File: AuthzClientCredentialsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AuthzClient getAuthzClient(String adapterConfig) {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getConfigurationStream(adapterConfig));

    return AuthzClient.create(new Configuration(deployment.getAuthServerBaseUrl(), deployment.getRealm(), deployment.getResourceName(), deployment.getResourceCredentials(), deployment.getClient()), new ClientAuthenticator() {
        @Override
        public void configureClientCredentials(Map<String, List<String>> requestParams, Map<String, String> requestHeaders) {
            Map<String, String> formparams = new HashMap<>();
            ClientCredentialsProviderUtils.setClientCredentials(deployment, requestHeaders, formparams);
            for (Entry<String, String> param : formparams.entrySet()) {
                requestParams.put(param.getKey(), Arrays.asList(param.getValue()));
            }
        }
    });
}
 
Example 11
Source File: IdentityServiceDeploymentFactoryBean.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public KeycloakDeployment getObject() throws Exception
{
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(this.identityServiceConfig);

    // Set client with custom timeout values if client was created by the KeycloakDeploymentBuilder.
    // This can be removed if the future versions of Keycloak accept timeout values through the config.
    if (deployment.getClient() != null)
    {
        int connectionTimeout = identityServiceConfig.getClientConnectionTimeout();
        int socketTimeout = identityServiceConfig.getClientSocketTimeout();
        HttpClient client = new HttpClientBuilder()
                .establishConnectionTimeout(connectionTimeout, TimeUnit.MILLISECONDS)
                .socketTimeout(socketTimeout, TimeUnit.MILLISECONDS)
                .build(this.identityServiceConfig);
        deployment.setClient(client);

        if (logger.isDebugEnabled())
        {
            logger.debug("Created HttpClient for Keycloak deployment with connection timeout: "+ connectionTimeout + " ms, socket timeout: "+ socketTimeout+" ms.");
        }
    }
    else
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("HttpClient for Keycloak deployment was not set.");
        }
    }

    if (logger.isInfoEnabled())
    {
        logger.info("Keycloak JWKS URL: " + deployment.getJwksUrl());
        logger.info("Keycloak Realm: " + deployment.getRealm());
        logger.info("Keycloak Client ID: " + deployment.getResourceName());
    }
    
    return deployment;
}
 
Example 12
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testPathConfigurationPrecendenceWhenLazyLoadingPaths() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-paths.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/resourcea");
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);

    assertFalse(context.isGranted());
    assertEquals(403, TestResponse.class.cast(httpFacade.getResponse()).getStatus());

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();

    httpFacade = createHttpFacade("/api/resourcea", token);

    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());

    httpFacade = createHttpFacade("/");

    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
}
 
Example 13
Source File: KeycloakAuthFilter.java    From keycloak-dropwizard-integration with Apache License 2.0 4 votes vote down vote up
public void initializeKeycloak() {
    KeycloakDeployment kd = KeycloakDeploymentBuilder.build(adapterConfig);
    deploymentContext = new AdapterDeploymentContext(kd);
}
 
Example 14
Source File: KeycloakJWTCallerPrincipalFactory.java    From thorntail with Apache License 2.0 4 votes vote down vote up
public static void createDeploymentFromStream(InputStream keycloakJsonStream) {
    deployment = KeycloakDeploymentBuilder.build(keycloakJsonStream);
}
 
Example 15
Source File: KeycloakInstalled.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public KeycloakInstalled() {
    InputStream config = Thread.currentThread().getContextClassLoader().getResourceAsStream(KEYCLOAK_JSON);
    deployment = KeycloakDeploymentBuilder.build(config);
}
 
Example 16
Source File: ClaimInformationPointProviderTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClaimInformationPointProvider getClaimInformationProviderForPath(String path, String providerName) {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getClass().getResourceAsStream("/authorization-test/enforcer-config-claims-provider.json"));
    deployment.setClient(HttpClients.createDefault());
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    Map<String, ClaimInformationPointProviderFactory> providers = policyEnforcer.getClaimInformationPointProviderFactories();

    PathConfig pathConfig = policyEnforcer.getPaths().get(path);

    assertNotNull(pathConfig);

    Map<String, Map<String, Object>> cipConfig = pathConfig.getClaimInformationPointConfig();

    assertNotNull(cipConfig);

    ClaimInformationPointProviderFactory factory = providers.get(providerName);

    assertNotNull(factory);

    Map<String, Object> claimsConfig = cipConfig.get(providerName);

    return factory.create(claimsConfig);
}
 
Example 17
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testEnforceEntitlementAccessWithClaimsWithoutBearerToken() {
    initAuthorizationSettings(getClientResource("resource-server-test"));

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-entitlement-claims-test.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    HashMap<String, List<String>> headers = new HashMap<>();
    HashMap<String, List<String>> parameters = new HashMap<>();

    AuthzClient authzClient = getAuthzClient("enforcer-entitlement-claims-test.json");
    String token = authzClient.obtainAccessToken("marta", "password").getToken();

    AuthorizationContext context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());
    assertEquals(1, context.getPermissions().size());
    Permission permission = context.getPermissions().get(0);
    assertEquals(parameters.get("withdrawal.amount").get(0), permission.getClaims().get("withdrawal.amount").iterator().next());

    parameters.put("withdrawal.amount", Arrays.asList("200"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("10"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));

    assertTrue(context.isGranted());

    assertEquals(1, context.getPermissions().size());
    permission = context.getPermissions().get(0);
    assertEquals(parameters.get("withdrawal.amount").get(0), permission.getClaims().get("withdrawal.amount").iterator().next());
}
 
Example 18
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 3 votes vote down vote up
@Test
public void testEnforceEntitlementAccessWithClaimsWithBearerToken() {
    initAuthorizationSettings(getClientResource("resource-server-test"));

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-entitlement-claims-test.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    HashMap<String, List<String>> headers = new HashMap<>();
    HashMap<String, List<String>> parameters = new HashMap<>();

    AuthzClient authzClient = getAuthzClient("enforcer-entitlement-claims-test.json");
    String token = authzClient.obtainAccessToken("marta", "password").getToken();

    headers.put("Authorization", Arrays.asList("Bearer " + token));

    AuthorizationContext context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("200"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("10"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));

    assertTrue(context.isGranted());
}
 
Example 19
Source File: Utils.java    From FROST-Server with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Create a new KeycloakDeployment from settings loaded from the given
 * CoreSettings.
 *
 * @param coreSettings The CoreSettings to create a KeycloakDeployment from.
 * @return the new KeycloakDeployment.
 */
public static KeycloakDeployment resolveDeployment(CoreSettings coreSettings) {
    String keycloakConfig = getKeycloakConfig(coreSettings);
    InputStream input = new ByteArrayInputStream(keycloakConfig.getBytes(StringHelper.UTF8));
    return KeycloakDeploymentBuilder.build(input);
}
 
Example 20
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 2 votes vote down vote up
@Test
public void testEnforceEntitlementAccessWithClaimsWithBearerTokenFromPublicClient() {
    initAuthorizationSettings(getClientResource("resource-server-test"));

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-entitlement-claims-test.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    HashMap<String, List<String>> headers = new HashMap<>();
    HashMap<String, List<String>> parameters = new HashMap<>();

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");

    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();

    headers.put("Authorization", Arrays.asList("Bearer " + token));

    AuthorizationContext context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("200"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("50"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());

    parameters.put("withdrawal.amount", Arrays.asList("10"));

    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));

    assertTrue(context.isGranted());
}