Search in sources :

Example 11 with PolicyEnforcer

use of org.keycloak.adapters.authorization.PolicyEnforcer in project keycloak by keycloak.

the class PolicyEnforcerClaimsTest method testEnforceEntitlementAccessWithClaimsWithBearerTokenFromPublicClient.

@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());
}
Also used : HashMap(java.util.HashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) List(java.util.List) AuthorizationContext(org.keycloak.AuthorizationContext) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 12 with PolicyEnforcer

use of org.keycloak.adapters.authorization.PolicyEnforcer in project keycloak by keycloak.

the class AuthenticatedActionsHandler method isAuthorized.

private boolean isAuthorized() {
    PolicyEnforcer policyEnforcer = this.deployment.getPolicyEnforcer();
    if (policyEnforcer == null) {
        log.debugv("Policy enforcement is disabled.");
        return true;
    }
    try {
        OIDCHttpFacade facade = (OIDCHttpFacade) this.facade;
        AuthorizationContext authorizationContext = policyEnforcer.enforce(facade);
        RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) facade.getSecurityContext();
        if (session != null) {
            session.setAuthorizationContext(authorizationContext);
        }
        return authorizationContext.isGranted();
    } catch (Exception e) {
        throw new RuntimeException("Failed to enforce policy decisions.", e);
    }
}
Also used : PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) AuthorizationContext(org.keycloak.AuthorizationContext) IOException(java.io.IOException)

Example 13 with PolicyEnforcer

use of org.keycloak.adapters.authorization.PolicyEnforcer in project keycloak by keycloak.

the class KeycloakDeploymentBuilder method internalBuild.

protected KeycloakDeployment internalBuild(final AdapterConfig adapterConfig) {
    if (adapterConfig.getRealm() == null)
        throw new RuntimeException("Must set 'realm' in config");
    deployment.setRealm(adapterConfig.getRealm());
    String resource = adapterConfig.getResource();
    if (resource == null)
        throw new RuntimeException("Must set 'resource' in config");
    deployment.setResourceName(resource);
    String realmKeyPem = adapterConfig.getRealmKey();
    if (realmKeyPem != null) {
        PublicKey realmKey;
        try {
            realmKey = PemUtils.decodePublicKey(realmKeyPem);
            HardcodedPublicKeyLocator pkLocator = new HardcodedPublicKeyLocator(realmKey);
            deployment.setPublicKeyLocator(pkLocator);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        JWKPublicKeyLocator pkLocator = new JWKPublicKeyLocator();
        deployment.setPublicKeyLocator(pkLocator);
    }
    if (adapterConfig.getSslRequired() != null) {
        deployment.setSslRequired(SslRequired.valueOf(adapterConfig.getSslRequired().toUpperCase()));
    } else {
        deployment.setSslRequired(SslRequired.EXTERNAL);
    }
    if (adapterConfig.getConfidentialPort() != -1) {
        deployment.setConfidentialPort(adapterConfig.getConfidentialPort());
    }
    if (adapterConfig.getTokenStore() != null) {
        deployment.setTokenStore(TokenStore.valueOf(adapterConfig.getTokenStore().toUpperCase()));
    } else {
        deployment.setTokenStore(TokenStore.SESSION);
    }
    if (adapterConfig.getTokenCookiePath() != null) {
        deployment.setAdapterStateCookiePath(adapterConfig.getTokenCookiePath());
    }
    if (adapterConfig.getPrincipalAttribute() != null)
        deployment.setPrincipalAttribute(adapterConfig.getPrincipalAttribute());
    deployment.setResourceCredentials(adapterConfig.getCredentials());
    deployment.setClientAuthenticator(ClientCredentialsProviderUtils.bootstrapClientAuthenticator(deployment));
    deployment.setPublicClient(adapterConfig.isPublicClient());
    deployment.setUseResourceRoleMappings(adapterConfig.isUseResourceRoleMappings());
    deployment.setExposeToken(adapterConfig.isExposeToken());
    if (adapterConfig.isCors()) {
        deployment.setCors(true);
        deployment.setCorsMaxAge(adapterConfig.getCorsMaxAge());
        deployment.setCorsAllowedHeaders(adapterConfig.getCorsAllowedHeaders());
        deployment.setCorsAllowedMethods(adapterConfig.getCorsAllowedMethods());
        deployment.setCorsExposedHeaders(adapterConfig.getCorsExposedHeaders());
    }
    // https://tools.ietf.org/html/rfc7636
    if (adapterConfig.isPkce()) {
        deployment.setPkce(true);
    }
    deployment.setBearerOnly(adapterConfig.isBearerOnly());
    deployment.setAutodetectBearerOnly(adapterConfig.isAutodetectBearerOnly());
    deployment.setEnableBasicAuth(adapterConfig.isEnableBasicAuth());
    deployment.setAlwaysRefreshToken(adapterConfig.isAlwaysRefreshToken());
    deployment.setRegisterNodeAtStartup(adapterConfig.isRegisterNodeAtStartup());
    deployment.setRegisterNodePeriod(adapterConfig.getRegisterNodePeriod());
    deployment.setTokenMinimumTimeToLive(adapterConfig.getTokenMinimumTimeToLive());
    deployment.setMinTimeBetweenJwksRequests(adapterConfig.getMinTimeBetweenJwksRequests());
    deployment.setPublicKeyCacheTtl(adapterConfig.getPublicKeyCacheTtl());
    deployment.setIgnoreOAuthQueryParameter(adapterConfig.isIgnoreOAuthQueryParameter());
    deployment.setRewriteRedirectRules(adapterConfig.getRedirectRewriteRules());
    deployment.setVerifyTokenAudience(adapterConfig.isVerifyTokenAudience());
    if (realmKeyPem == null && adapterConfig.isBearerOnly() && adapterConfig.getAuthServerUrl() == null) {
        throw new IllegalArgumentException("For bearer auth, you must set the realm-public-key or auth-server-url");
    }
    if (adapterConfig.getAuthServerUrl() == null && (!deployment.isBearerOnly() || realmKeyPem == null)) {
        throw new RuntimeException("You must specify auth-server-url");
    }
    deployment.setClient(createHttpClientProducer(adapterConfig));
    deployment.setAuthServerBaseUrl(adapterConfig);
    if (adapterConfig.getTurnOffChangeSessionIdOnLogin() != null) {
        deployment.setTurnOffChangeSessionIdOnLogin(adapterConfig.getTurnOffChangeSessionIdOnLogin());
    }
    final PolicyEnforcerConfig policyEnforcerConfig = adapterConfig.getPolicyEnforcerConfig();
    if (policyEnforcerConfig != null) {
        deployment.setPolicyEnforcer(new Callable<PolicyEnforcer>() {

            PolicyEnforcer policyEnforcer;

            @Override
            public PolicyEnforcer call() {
                if (policyEnforcer == null) {
                    synchronized (deployment) {
                        if (policyEnforcer == null) {
                            policyEnforcer = new PolicyEnforcer(deployment, adapterConfig);
                        }
                    }
                }
                return policyEnforcer;
            }
        });
    }
    return deployment;
}
Also used : HardcodedPublicKeyLocator(org.keycloak.adapters.rotation.HardcodedPublicKeyLocator) PublicKey(java.security.PublicKey) JWKPublicKeyLocator(org.keycloak.adapters.rotation.JWKPublicKeyLocator) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) IOException(java.io.IOException) PolicyEnforcerConfig(org.keycloak.representations.adapters.config.PolicyEnforcerConfig)

Example 14 with PolicyEnforcer

use of org.keycloak.adapters.authorization.PolicyEnforcer in project keycloak by keycloak.

the class PolicyEnforcerClaimsTest method testEnforceEntitlementAccessWithClaimsWithoutBearerToken.

@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());
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) HashMap(java.util.HashMap) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) Permission(org.keycloak.representations.idm.authorization.Permission) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) List(java.util.List) AuthorizationContext(org.keycloak.AuthorizationContext) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 15 with PolicyEnforcer

use of org.keycloak.adapters.authorization.PolicyEnforcer in project keycloak by keycloak.

the class PolicyEnforcerClaimsTest method testEnforceEntitlementAccessWithClaimsWithBearerToken.

@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());
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) HashMap(java.util.HashMap) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) List(java.util.List) AuthorizationContext(org.keycloak.AuthorizationContext) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Aggregations

PolicyEnforcer (org.keycloak.adapters.authorization.PolicyEnforcer)22 KeycloakDeployment (org.keycloak.adapters.KeycloakDeployment)20 Test (org.junit.Test)19 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)19 AuthorizationContext (org.keycloak.AuthorizationContext)17 OIDCHttpFacade (org.keycloak.adapters.OIDCHttpFacade)11 OAuthClient (org.keycloak.testsuite.util.OAuthClient)10 HashMap (java.util.HashMap)5 ClientResource (org.keycloak.admin.client.resource.ClientResource)5 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)5 List (java.util.List)4 PermissionsResource (org.keycloak.admin.client.resource.PermissionsResource)4 AuthzClient (org.keycloak.authorization.client.AuthzClient)4 Permission (org.keycloak.representations.idm.authorization.Permission)4 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)4 PathConfig (org.keycloak.representations.adapters.config.PolicyEnforcerConfig.PathConfig)3 IOException (java.io.IOException)2 Map (java.util.Map)2 Set (java.util.Set)2 PolicyEnforcerConfig (org.keycloak.representations.adapters.config.PolicyEnforcerConfig)2