org.keycloak.adapters.KeycloakDeploymentBuilder Java Examples

The following examples show how to use org.keycloak.adapters.KeycloakDeploymentBuilder. 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: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCustomClaimProvider() {
    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);

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

    assertTrue(context.isGranted());
    assertEquals("test", claims.get("resolved-claim").iterator().next());
}
 
Example #2
Source File: KeycloakPolicyEnforcerAuthorizer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public void init(OidcConfig oidcConfig, KeycloakPolicyEnforcerConfig config, HttpConfiguration httpConfiguration) {
    AdapterConfig adapterConfig = new AdapterConfig();
    String authServerUrl = oidcConfig.defaultTenant.getAuthServerUrl().get();

    try {
        adapterConfig.setRealm(authServerUrl.substring(authServerUrl.lastIndexOf('/') + 1));
        adapterConfig.setAuthServerUrl(authServerUrl.substring(0, authServerUrl.lastIndexOf("/realms")));
    } catch (Exception cause) {
        throw new RuntimeException("Failed to parse the realm name.", cause);
    }

    adapterConfig.setResource(oidcConfig.defaultTenant.getClientId().get());
    adapterConfig.setCredentials(getCredentials(oidcConfig.defaultTenant));

    PolicyEnforcerConfig enforcerConfig = getPolicyEnforcerConfig(config, adapterConfig);

    if (enforcerConfig == null) {
        return;
    }

    adapterConfig.setPolicyEnforcerConfig(enforcerConfig);

    this.readTimeout = httpConfiguration.readTimeout.toMillis();
    this.delegate = new KeycloakAdapterPolicyEnforcer(
            new PolicyEnforcer(KeycloakDeploymentBuilder.build(adapterConfig), adapterConfig));
}
 
Example #3
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 #4
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testPublicEndpointNoBearerAbortRequest() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only.json"));
    OIDCHttpFacade httpFacade = createHttpFacade("/api/public");
    AuthenticatedActionsHandler handler = new AuthenticatedActionsHandler(deployment, httpFacade);

    assertTrue(handler.handledRequest());

    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);
    handler = new AuthenticatedActionsHandler(deployment, httpFacade);

    assertFalse(handler.handledRequest());
}
 
Example #5
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 #6
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 #7
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultWWWAuthenticateCorsHeader() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-disabled-enforce-mode-path.json"));

    deployment.setCors(true);
    Map<String, List<String>> headers = new HashMap<>();

    headers.put(CorsHeaders.ORIGIN,Arrays.asList("http://localhost:8180"));

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");
    String token = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), null).getAccessToken();
    OIDCHttpFacade httpFacade = createHttpFacade("http://server/api/resource/public", HttpMethod.OPTIONS, token, headers, Collections.emptyMap(), null, deployment);
    new AuthenticatedActionsHandler(deployment, httpFacade).handledRequest();
    assertEquals(HttpHeaders.WWW_AUTHENTICATE, headers.get(CorsHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).get(0));
}
 
Example #8
Source File: LotteryApplication.java    From keycloak-dropwizard-integration with Apache License 2.0 6 votes vote down vote up
@Override
public void run(LotteryConfiguration configuration, Environment environment) {

    // tag::keycloak[]
    KeycloakDeployment keycloakDeployment =
            KeycloakDeploymentBuilder.build(configuration.getKeycloakConfiguration());
    JaxrsBearerTokenFilterImpl filter = new DropwizardBearerTokenFilterImpl(keycloakDeployment);
    environment.jersey().register(filter);
    // end::keycloak[]

    environment.jersey().register(new DrawRessource());

    // support annotation @RolesAllowed
    // tag::roles[]
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    // end::roles[]

}
 
Example #9
Source File: EnforcerConfigTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testPathConfigClaimInformationPoint() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getClass().getResourceAsStream("/authorization-test/enforcer-config-path-cip.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    Map<String, PolicyEnforcerConfig.PathConfig> paths = policyEnforcer.getPaths();

    assertEquals(1, paths.size());

    PathConfig pathConfig = paths.values().iterator().next();
    Map<String, Map<String, Object>> cipConfig = pathConfig.getClaimInformationPointConfig();

    assertEquals(1, cipConfig.size());

    Map<String, Object> claims = cipConfig.get("claims");

    assertNotNull(claims);

    assertEquals(3, claims.size());
    assertEquals("{request.parameter['a']}", claims.get("claim-a"));
    assertEquals("{request.header['b']}", claims.get("claim-b"));
    assertEquals("{request.cookie['c']}", claims.get("claim-c"));
}
 
Example #10
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 #11
Source File: MultiTenantResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KeycloakDeployment resolve(HttpFacade.Request request) {

    String path = request.getURI();
    int multitenantIndex = path.indexOf("multi-tenant/");
    if (multitenantIndex == -1) {
        throw new IllegalStateException("Not able to resolve realm from the request path!");
    }

    String realm = path.substring(path.indexOf("multi-tenant/")).split("/")[1];
    if (realm.contains("?")) {
        realm = realm.split("\\?")[0];
    }
    
    InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/" + realm + "-keycloak.json");

    if (is == null) {
        throw new IllegalStateException("Not able to find the file /" + realm + "-keycloak.json");
    }

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(is);
    return deployment;
}
 
Example #12
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 #13
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotAuthenticatedDenyUnmapedPath() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/unmmaped");
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);

    assertFalse(context.isGranted());
    TestResponse response = TestResponse.class.cast(httpFacade.getResponse());
    assertEquals(403, response.getStatus());
}
 
Example #14
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testMappedPathEnforcementModeDisabled() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-disabled-enforce-mode-path.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();

    OIDCHttpFacade httpFacade = createHttpFacade("/api/resource/public");
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());

    httpFacade = createHttpFacade("/api/resourceb");
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    TestResponse response = TestResponse.class.cast(httpFacade.getResponse());
    assertEquals(403, response.getStatus());

    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");
    String token = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), null).getAccessToken();

    httpFacade = createHttpFacade("/api/resourcea", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());

    httpFacade = createHttpFacade("/api/resourceb", token);
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    response = TestResponse.class.cast(httpFacade.getResponse());
    assertEquals(403, response.getStatus());

    httpFacade = createHttpFacade("/api/resource/public", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
}
 
Example #15
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnforcementModeDisabled() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-disabled-enforce-mode.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();

    OIDCHttpFacade httpFacade = createHttpFacade("/api/resource/public");
    policyEnforcer.enforce(httpFacade);
    TestResponse response = TestResponse.class.cast(httpFacade.getResponse());
    assertEquals(401, response.getStatus());
}
 
Example #16
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsingSubjectToken() {
    ClientResource clientResource = getClientResource(RESOURCE_SERVER_CLIENT_ID);
    ResourceRepresentation resource = createResource(clientResource, "Resource Subject Token", "/api/check-subject-token");

    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();

    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getName());
    permission.addPolicy("Only User Policy");

    PermissionsResource permissions = clientResource.authorization().permissions();
    permissions.resource().create(permission).close();

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/check-subject-token");
    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/check-subject-token", token);

    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
}
 
Example #17
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsingInvalidToken() {
    ClientResource clientResource = getClientResource(RESOURCE_SERVER_CLIENT_ID);
    ResourceRepresentation resource = createResource(clientResource, "Resource Subject Invalid Token", "/api/check-subject-token");

    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();

    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getName());
    permission.addPolicy("Only User Policy");

    PermissionsResource permissions = clientResource.authorization().permissions();
    permissions.resource().create(permission).close();

    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-bearer-only.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/check-subject-token");

    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/check-subject-token", token);

    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    
    oauth.doLogout(response.getRefreshToken(), null);

    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
}
 
Example #18
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 #19
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 #20
Source File: PathBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean cacheConfiguration(String key, File config) {
    try {
        InputStream is = new FileInputStream(config);
        KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(is);
        cache.put(key, deployment);
        return true;
    } catch (FileNotFoundException | RuntimeException e) {
        log.warn("Can't cache " + config + ": " + e.getMessage(), e);
        return false;
    }
}
 
Example #21
Source File: UndertowKeycloakEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdapterDeploymentContext getDeploymentContext() {
    if (configResolver != null) {
        LOG.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolver.getClass());
        return new AdapterDeploymentContext(configResolver);
    } else if (adapterConfig != null) {
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(adapterConfig);
        return new AdapterDeploymentContext(kd);
    }

    LOG.warning("Adapter is unconfigured, Keycloak will deny every request");
    return new AdapterDeploymentContext();
}
 
Example #22
Source File: CxfKeycloakAuthHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AdapterDeploymentContext buildDeploymentContext() {
    if (configResolver != null) {
        LOG.log(Level.INFO, "Using {0} to resolve Keycloak configuration on a per-request basis.", configResolver.getClass());
        return new AdapterDeploymentContext(configResolver);
    } else if (adapterConfig != null) {
        KeycloakDeployment kd = KeycloakDeploymentBuilder.build(adapterConfig);
        return new AdapterDeploymentContext(kd);
    }

    LOG.warning("Adapter is unconfigured, Keycloak will deny every request");
    return new AdapterDeploymentContext();
}
 
Example #23
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String readToken(String client) throws Exception {
    String json = getTokenResponse(client);
    if (json == null) return null;


    if (json != null) {
        try {
            AccessTokenResponse tokenResponse = JsonSerialization.readValue(json, AccessTokenResponse.class);
            if (Time.currentTime() < tokenResponse.getExpiresIn()) {
                return tokenResponse.getToken();
            }
            AdapterConfig config = getConfig();
            KeycloakInstalled installed = new KeycloakInstalled(KeycloakDeploymentBuilder.build(config));
            installed.refreshToken(tokenResponse.getRefreshToken());
            processResponse(installed, client);
            return tokenResponse.getToken();
        } catch (Exception e) {
            File tokenFile = getTokenFilePath(client);
            if (tokenFile.exists()) {
                tokenFile.delete();
            }

            return null;
        }
    }
    return null;

}
 
Example #24
Source File: KcinitDriver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void doConsoleLogin() throws Exception {
    String masterClient = getMasterClient();
    AdapterConfig config = getConfig();
    KeycloakInstalled installed = new KeycloakInstalled(KeycloakDeploymentBuilder.build(config));
    //System.err.println("calling loginCommandLine");
    if (!installed.loginCommandLine()) {
        System.exit(1);
    }
    processResponse(installed, masterClient);
}
 
Example #25
Source File: AdapterDeploymentContextFactoryBean.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakDeployment loadKeycloakDeployment() throws IOException {
    if (!keycloakConfigFileResource.isReadable()) {
        throw new FileNotFoundException(String.format("Unable to locate Keycloak configuration file: %s",
                keycloakConfigFileResource.getFilename()));
    }

    return KeycloakDeploymentBuilder.build(keycloakConfigFileResource.getInputStream());
}
 
Example #26
Source File: KeycloakSpringBootConfigResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    if (keycloakDeployment != null) {
        return keycloakDeployment;
    }

    keycloakDeployment = KeycloakDeploymentBuilder.build(adapterConfig);

    return keycloakDeployment;
}
 
Example #27
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 #28
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 #29
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 #30
Source File: ServerRuntime.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public void startup(final IStartupCompleteListener completeListener) {
    new Thread(ServerRuntime.class.getSimpleName()) {
        public void run() {
            try {
                Map<String, String> contextParameter = new HashMap<>();
                contextParameter.put("resteasy.guice.stage", environment.toUpperCase());
                contextParameter.put("resteasy.logger.type", "SLF4J");
                contextParameter.put("resteasy.servlet.mapping.prefix", "/");
                contextParameter.put("javax.ws.rs.Application", options.applicationConfiguration.getName());

                startupJetty(contextParameter,
                        Arrays.asList(resteasyContextListener, swaggerContextListener),
                        Arrays.asList(new FilterMappingHolder(
                                        new KeycloakOIDCFilter(
                                                facade -> KeycloakDeploymentBuilder.build(keycloakAdapterConfig)), "/keycloak/*"),
                                new FilterMappingHolder(new WroFilter(), "/text/*")),
                        Arrays.asList(new HttpServletHolder(httpServletDispatcher, "/*"),
                                new HttpServletHolder(new JSAPIServlet(), "/rest-js")),
                        FileUtilities.buildPath(System.getProperty("user.dir"), resourceDir));
                log.info("Jetty has successfully started.");
                completeListener.onComplete();
            } catch (Exception e) {
                log.error(e.getLocalizedMessage(), e);
            }
        }
    }.start();
}