org.keycloak.adapters.KeycloakDeployment Java Examples

The following examples show how to use org.keycloak.adapters.KeycloakDeployment. 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: JWTClientSecretCredentialsProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void init(KeycloakDeployment deployment, Object config) {
    if (!(config instanceof Map)) {
        throw new RuntimeException("Configuration of jwt credentials by client secret is missing or incorrect for client '" + deployment.getResourceName() + "'. Check your adapter configuration");
    }

    Map<String, Object> cfg = (Map<String, Object>) config;
    String clientSecretString = (String) cfg.get("secret");
    if (clientSecretString == null) {
        throw new RuntimeException("Missing parameter secret-jwt in configuration of jwt for client " + deployment.getResourceName());
    }

    String clientSecretJwtAlg = (String) cfg.get("algorithm");
    if (clientSecretJwtAlg == null) {
        // "algorithm" field is optional. fallback to HS256.
        setClientSecret(clientSecretString); 
    } else if (isValidClientSecretJwtAlg(clientSecretJwtAlg)) {
        setClientSecret(clientSecretString, clientSecretJwtAlg); 
    } else {
        // invalid "algorithm" field
        throw new RuntimeException("Invalid parameter secret-jwt in configuration of jwt for client " + deployment.getResourceName());
    }
}
 
Example #2
Source File: ProductServiceAccountServlet.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void setTokens(HttpServletRequest req, KeycloakDeployment deployment, AccessTokenResponse tokenResponse) throws IOException, VerificationException {
    String token = tokenResponse.getToken();
    String refreshToken = tokenResponse.getRefreshToken();
    AdapterTokenVerifier.VerifiedTokens parsedTokens = AdapterTokenVerifier.verifyTokens(token, tokenResponse.getIdToken(), deployment);
    AccessToken tokenParsed = parsedTokens.getAccessToken();
    req.getSession().setAttribute(TOKEN, token);
    req.getSession().setAttribute(REFRESH_TOKEN, refreshToken);
    req.getSession().setAttribute(TOKEN_PARSED, tokenParsed);
}
 
Example #3
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 #4
Source File: HierarchicalPathBasedKeycloakConfigResolverTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private PathBasedKeycloakConfigResolver populate(PathBasedKeycloakConfigResolver resolver, boolean fallback)
        throws Exception {
    Field f = PathBasedKeycloakConfigResolver.class.getDeclaredField("cache");
    f.setAccessible(true);
    Map<String, KeycloakDeployment> cache = (Map<String, KeycloakDeployment>) f.get(resolver);
    cache.clear();
    cache.put("a-b-c-d-e", newKeycloakDeployment("a-b-c-d-e"));
    cache.put("a-b-c-d", newKeycloakDeployment("a-b-c-d"));
    cache.put("a-b-c", newKeycloakDeployment("a-b-c"));
    cache.put("a-b", newKeycloakDeployment("a-b"));
    cache.put("a", newKeycloakDeployment("a"));
    if (fallback) {
        cache.put("", newKeycloakDeployment(""));
    }

    return resolver;
}
 
Example #5
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 #6
Source File: AbstractUndertowKeycloakAuthMech.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void registerNotifications(final SecurityContext securityContext) {

        final NotificationReceiver logoutReceiver = new NotificationReceiver() {
            @Override
            public void handleNotification(SecurityNotification notification) {
                if (notification.getEventType() != SecurityNotification.EventType.LOGGED_OUT) return;

                HttpServerExchange exchange = notification.getExchange();
                UndertowHttpFacade facade = createFacade(exchange);
                KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
                KeycloakSecurityContext ksc = exchange.getAttachment(OIDCUndertowHttpFacade.KEYCLOAK_SECURITY_CONTEXT_KEY);
                if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
                    ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
                }
                AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
                tokenStore.logout();
            }
        };

        securityContext.registerNotificationReceiver(logoutReceiver);
    }
 
Example #7
Source File: JWKPublicKeyLocator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void sendRequest(KeycloakDeployment deployment) {
    if (log.isTraceEnabled()) {
        log.trace("Going to send request to retrieve new set of realm public keys for client " + deployment.getResourceName());
    }

    HttpGet getMethod = new HttpGet(deployment.getJwksUrl());
    try {
        JSONWebKeySet jwks = HttpAdapterUtils.sendJsonHttpRequest(deployment, getMethod, JSONWebKeySet.class);

        Map<String, PublicKey> publicKeys = JWKSUtils.getKeysForUse(jwks, JWK.Use.SIG);

        if (log.isDebugEnabled()) {
            log.debug("Realm public keys successfully retrieved for client " +  deployment.getResourceName() + ". New kids: " + publicKeys.keySet().toString());
        }

        // Update current keys
        currentKeys.clear();
        currentKeys.putAll(publicKeys);

    } catch (HttpClientAdapterException e) {
        log.error("Error when sending request to retrieve realm keys", e);
    }
}
 
Example #8
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 #9
Source File: WildflyAuthenticationMechanism.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected ServletRequestAuthenticator createRequestAuthenticator(KeycloakDeployment deployment, HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {
    int confidentialPort = getConfidentilPort(exchange);
    AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
    return new WildflyRequestAuthenticator(facade, deployment,
            confidentialPort, securityContext, exchange, tokenStore);
}
 
Example #10
Source File: SpringSecurityAdapterTokenStoreFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AdapterTokenStore createAdapterTokenStore(KeycloakDeployment deployment, HttpServletRequest request, HttpServletResponse response) {
    Assert.notNull(deployment, "KeycloakDeployment is required");
    if (deployment.getTokenStore() == TokenStore.COOKIE) {
        return new SpringSecurityCookieTokenStore(deployment, request, response);
    }
    return new SpringSecurityTokenStore(deployment, request);
}
 
Example #11
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 #12
Source File: ProductServiceAccountServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void init() throws ServletException {
    String adapterConfigLocation = "/WEB-INF/keycloak.json";
    InputStream config = getServletContext().getResourceAsStream(adapterConfigLocation);
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(config);
    getServletContext().setAttribute(KeycloakDeployment.class.getName(), deployment);

    HttpClient client = new DefaultHttpClient();
    getServletContext().setAttribute(HttpClient.class.getName(), client);
}
 
Example #13
Source File: PathBasedKeycloakConfigResolverTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private PathBasedKeycloakConfigResolver populate(PathBasedKeycloakConfigResolver resolver, String context)
        throws Exception {
    Field f = PathBasedKeycloakConfigResolver.class.getDeclaredField("cache");
    f.setAccessible(true);
    Map<String, KeycloakDeployment> cache = (Map<String, KeycloakDeployment>) f.get(resolver);
    cache.clear();
    cache.put(context, new KeycloakDeployment());

    return resolver;
}
 
Example #14
Source File: ServletKeycloakAuthMech.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected RequestAuthenticator createRequestAuthenticator(KeycloakDeployment deployment, HttpServerExchange exchange, SecurityContext securityContext, UndertowHttpFacade facade) {

        int confidentialPort = getConfidentilPort(exchange);
        AdapterTokenStore tokenStore = getTokenStore(exchange, facade, deployment, securityContext);
        return new ServletRequestAuthenticator(facade, deployment,
                confidentialPort, securityContext, exchange, tokenStore);
    }
 
Example #15
Source File: AdapterDeploymentContextFactoryBeanTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakConfigResolver getKeycloakConfigResolver() {
    return new KeycloakConfigResolver() {
        @Override
        public KeycloakDeployment resolve(HttpFacade.Request facade) {
            return null;
        }
    };
}
 
Example #16
Source File: AbstractKeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void logoutInternal(Request request) {
    KeycloakSecurityContext ksc = (KeycloakSecurityContext)request.getAttribute(KeycloakSecurityContext.class.getName());
    if (ksc != null) {
        CatalinaHttpFacade facade = new OIDCCatalinaHttpFacade(request, null);
        KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
        if (ksc instanceof RefreshableKeycloakSecurityContext) {
            ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
        }

        AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
        tokenStore.logout();
        request.removeAttribute(KeycloakSecurityContext.class.getName());
    }
    request.setUserPrincipal(null);
}
 
Example #17
Source File: UndertowKeycloakConsumer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AdapterTokenStore getTokenStore(HttpServerExchange exchange, HttpFacade facade, KeycloakDeployment deployment, SecurityContext securityContext) {
    if (deployment.getTokenStore() == TokenStore.SESSION) {
        return new UndertowSessionTokenStore(exchange, deployment, userSessionManagement, securityContext);
    } else {
        return new UndertowCookieTokenStore(facade, deployment, securityContext);
    }
}
 
Example #18
Source File: JWTClientCredentialsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void setClientCredentials(KeycloakDeployment deployment, Map<String, String> requestHeaders, Map<String, String> formParams) {
    String signedToken = createSignedRequestToken(deployment.getResourceName(), deployment.getRealmInfoUrl());

    formParams.put(OAuth2Constants.CLIENT_ASSERTION_TYPE, OAuth2Constants.CLIENT_ASSERTION_TYPE_JWT);
    formParams.put(OAuth2Constants.CLIENT_ASSERTION, signedToken);
}
 
Example #19
Source File: FilterRequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public FilterRequestAuthenticator(KeycloakDeployment deployment,
                                  AdapterTokenStore tokenStore,
                                  OIDCHttpFacade facade,
                                  HttpServletRequest request,
                                  int sslRedirectPort) {
    super(facade, deployment, tokenStore, sslRedirectPort);
    this.request = request;
}
 
Example #20
Source File: OfflineAccessPortalServlet.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private KeycloakDeployment getDeployment(HttpServletRequest servletRequest) throws ServletException {
    // The facade object is needed just if you have relative "auth-server-url" in keycloak.json. Otherwise you can call deploymentContext.resolveDeployment(null)
    HttpFacade facade = getFacade(servletRequest);

    AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) getServletContext().getAttribute(AdapterDeploymentContext.class.getName());
    if (deploymentContext == null) {
        throw new ServletException("AdapterDeploymentContext not set");
    }
    return deploymentContext.resolveDeployment(facade);
}
 
Example #21
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void logoutCurrent(Request request) {
    AdapterDeploymentContext deploymentContext = (AdapterDeploymentContext) request.getAttribute(AdapterDeploymentContext.class.getName());
    KeycloakSecurityContext ksc = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    if (ksc != null) {
        JettyHttpFacade facade = new OIDCJettyHttpFacade(request, null);
        KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade);
        if (ksc instanceof RefreshableKeycloakSecurityContext) {
            ((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
        }

        AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment);
        tokenStore.logout();
        request.removeAttribute(KeycloakSecurityContext.class.getName());
    }
}
 
Example #22
Source File: AbstractKeycloakAuthenticatorValve.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AdapterTokenStore getTokenStore(Request request, HttpFacade facade, KeycloakDeployment resolvedDeployment) {
    AdapterTokenStore store = (AdapterTokenStore)request.getNote(TOKEN_STORE_NOTE);
    if (store != null) {
        return store;
    }

    if (resolvedDeployment.getTokenStore() == TokenStore.SESSION) {
        store = createSessionTokenStore(request, resolvedDeployment);
    } else {
        store = new CatalinaCookieTokenStore(request, facade, resolvedDeployment, createPrincipalFactory());
    }

    request.setNote(TOKEN_STORE_NOTE, store);
    return store;
}
 
Example #23
Source File: JWTClientCredentialsProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void init(KeycloakDeployment deployment, Object config) {
    if (!(config instanceof Map)) {
        throw new RuntimeException("Configuration of jwt credentials is missing or incorrect for client '" + deployment.getResourceName() + "'. Check your adapter configuration");
    }

    Map<String, Object> cfg = (Map<String, Object>) config;

    String clientKeystoreFile =  (String) cfg.get("client-keystore-file");
    if (clientKeystoreFile == null) {
        throw new RuntimeException("Missing parameter client-keystore-file in configuration of jwt for client " + deployment.getResourceName());
    }

    String clientKeystoreType = (String) cfg.get("client-keystore-type");
    KeystoreUtil.KeystoreFormat clientKeystoreFormat = clientKeystoreType==null ? KeystoreUtil.KeystoreFormat.JKS : Enum.valueOf(KeystoreUtil.KeystoreFormat.class, clientKeystoreType.toUpperCase());

    String clientKeystorePassword =  (String) cfg.get("client-keystore-password");
    if (clientKeystorePassword == null) {
        throw new RuntimeException("Missing parameter client-keystore-password in configuration of jwt for client " + deployment.getResourceName());
    }

    String clientKeyPassword = (String) cfg.get("client-key-password");
    if (clientKeyPassword == null) {
        clientKeyPassword = clientKeystorePassword;
    }

    String clientKeyAlias =  (String) cfg.get("client-key-alias");
    if (clientKeyAlias == null) {
        clientKeyAlias = deployment.getResourceName();
    }

    KeyPair keyPair = KeystoreUtil.loadKeyPairFromKeystore(clientKeystoreFile, clientKeystorePassword, clientKeyPassword, clientKeyAlias, clientKeystoreFormat);
    setupKeyPair(keyPair);

    this.tokenTimeout = asInt(cfg, "token-timeout", 10);
}
 
Example #24
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public SpringSecurityCookieTokenStore(
        KeycloakDeployment deployment,
        HttpServletRequest request,
        HttpServletResponse response) {
    super(deployment, request);
    Assert.notNull(response, "HttpServletResponse is required");
    this.deployment = deployment;
    this.facade = new SimpleHttpFacade(request, response);
}
 
Example #25
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 #26
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 #27
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 #28
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 #29
Source File: PolicyEnforcer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public PolicyEnforcer(KeycloakDeployment deployment, AdapterConfig adapterConfig) {
    this.deployment = deployment;
    this.enforcerConfig = adapterConfig.getPolicyEnforcerConfig();
    Configuration configuration = new Configuration(adapterConfig.getAuthServerUrl(), adapterConfig.getRealm(), adapterConfig.getResource(), adapterConfig.getCredentials(), deployment.getClient());
    this.authzClient = AuthzClient.create(configuration, new ClientAuthenticator() {
        @Override
        public void configureClientCredentials(Map<String, List<String>> requestParams, Map<String, String> requestHeaders) {
            Map<String, String> formparams = new HashMap<>();
            ClientCredentialsProviderUtils.setClientCredentials(PolicyEnforcer.this.deployment, requestHeaders, formparams);
            for (Entry<String, String> param : formparams.entrySet()) {
                requestParams.put(param.getKey(), Arrays.asList(param.getValue()));
            }
        }
    });

    paths = configurePaths(this.authzClient.protection().resource(), this.enforcerConfig);
    pathMatcher = new PathConfigMatcher(paths, enforcerConfig, authzClient);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Initialization complete. Path configurations:");
        for (PathConfig pathConfig : this.paths.values()) {
            LOGGER.debug(pathConfig);
        }
    }

    loadClaimInformationPointProviders(ServiceLoader.load(ClaimInformationPointProviderFactory.class, ClaimInformationPointProviderFactory.class.getClassLoader()));
    loadClaimInformationPointProviders(ServiceLoader.load(ClaimInformationPointProviderFactory.class, Thread.currentThread().getContextClassLoader()));
}
 
Example #30
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());
}