org.keycloak.adapters.OIDCHttpFacade Java Examples

The following examples show how to use org.keycloak.adapters.OIDCHttpFacade. 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: 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 #2
Source File: HierarchicalPathBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    // we cached all available deployments initially and now we'll try to check them from
    // most specific to most general
    URI uri = URI.create(request.getURI());
    String path = uri.getPath();
    if (path != null) {
        while (path.startsWith("/")) {
            path = path.substring(1);
        }
        String[] segments = path.split("/");
        List<String> paths = collectPaths(segments);
        for (String pathFragment: paths) {
            KeycloakDeployment cachedDeployment = super.getCachedDeployment(pathFragment);
            if (cachedDeployment != null) {
                return cachedDeployment;
            }
        }
    }

    throw new IllegalStateException("Can't find Keycloak configuration related to URI path " + uri);
}
 
Example #3
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 #4
Source File: PolicyEnforcer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public AuthorizationContext enforce(OIDCHttpFacade facade) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debugv("Policy enforcement is enabled. Enforcing policy decisions for path [{0}].", facade.getRequest().getURI());
    }

    AuthorizationContext context = new KeycloakAdapterPolicyEnforcer(this).authorize(facade);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debugv("Policy enforcement result for path [{0}] is : {1}", facade.getRequest().getURI(), context.isGranted() ? "GRANTED" : "DENIED");
        LOGGER.debugv("Returning authorization context with permissions:");
        for (Permission permission : context.getPermissions()) {
            LOGGER.debug(permission);
        }
    }

    return context;
}
 
Example #5
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 #6
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean challenge(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, OIDCHttpFacade httpFacade) {
    if (isBearerAuthorization(httpFacade)) {
        HttpFacade.Response response = httpFacade.getResponse();
        AuthzClient authzClient = getAuthzClient();
        String ticket = getPermissionTicket(pathConfig, methodConfig, authzClient, httpFacade);

        if (ticket != null) {
            response.setStatus(401);
            response.setHeader("WWW-Authenticate", new StringBuilder("UMA realm=\"").append(authzClient.getConfiguration().getRealm()).append("\"").append(",as_uri=\"")
                    .append(authzClient.getServerConfiguration().getIssuer()).append("\"").append(",ticket=\"").append(ticket).append("\"").toString());
        } else {
            response.setStatus(403);
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending challenge");
        }

        return true;
    }

    handleAccessDenied(httpFacade);

    return true;
}
 
Example #7
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 #8
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private String getPermissionTicket(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, AuthzClient authzClient, OIDCHttpFacade httpFacade) {
    if (getEnforcerConfig().getUserManagedAccess() != null) {
        ProtectionResource protection = authzClient.protection();
        PermissionResource permission = protection.permission();
        PermissionRequest permissionRequest = new PermissionRequest();

        permissionRequest.setResourceId(pathConfig.getId());
        permissionRequest.setScopes(new HashSet<>(methodConfig.getScopes()));

        Map<String, List<String>> claims = resolveClaims(pathConfig, httpFacade);

        if (!claims.isEmpty()) {
            permissionRequest.setClaims(claims);
        }

        return permission.create(permissionRequest).getTicket();
    }

    return null;
}
 
Example #9
Source File: SpringSecurityCookieTokenStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void checkCurrentToken() {
    final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal =
            checkPrincipalFromCookie();
    if (principal != null) {
        final RefreshableKeycloakSecurityContext securityContext =
                principal.getKeycloakSecurityContext();
        KeycloakSecurityContext current = ((OIDCHttpFacade) facade).getSecurityContext();
        if (current != null) {
            securityContext.setAuthorizationContext(current.getAuthorizationContext());
        }
        final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
        final OidcKeycloakAccount account =
                new SimpleKeycloakAccount(principal, roles, securityContext);
        SecurityContextHolder.getContext()
                .setAuthentication(new KeycloakAuthenticationToken(account, false));
    } else {
        super.checkCurrentToken();
    }
    cookieChecked = true;
}
 
Example #10
Source File: KeycloakAuthenticatedActionsFilter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if (request.getAttribute(FILTER_APPLIED) != null) {
        filterChain.doFilter(request, response);
        return;
    }

    request.setAttribute(FILTER_APPLIED, Boolean.TRUE);

    KeycloakSecurityContext keycloakSecurityContext = getKeycloakPrincipal();

    if (keycloakSecurityContext instanceof RefreshableKeycloakSecurityContext) {
        HttpFacade facade = new SimpleHttpFacade((HttpServletRequest) request, (HttpServletResponse) response);
        KeycloakDeployment deployment = resolveDeployment(request, response);
        AuthenticatedActionsHandler actions = new AuthenticatedActionsHandler(deployment, OIDCHttpFacade.class.cast(facade));
        if (actions.handledRequest()) {
            return;
        }
    }

    filterChain.doFilter(request, response);
}
 
Example #11
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean isBearerAuthorization(OIDCHttpFacade httpFacade) {
    List<String> authHeaders = httpFacade.getRequest().getHeaders("Authorization");

    if (authHeaders != null) {
        for (String authHeader : authHeaders) {
            String[] split = authHeader.trim().split("\\s+");
            if (split == null || split.length != 2) continue;
            if (!split[0].equalsIgnoreCase("Bearer")) continue;
            return true;
        }
    }

    return getPolicyEnforcer().getDeployment().isBearerOnly();
}
 
Example #12
Source File: KeycloakSecurityContextPlaceHolderResolver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> resolve(String placeHolder, HttpFacade httpFacade) {
    String source = placeHolder.substring(placeHolder.indexOf('.') + 1);
    OIDCHttpFacade oidcHttpFacade = OIDCHttpFacade.class.cast(httpFacade);
    KeycloakSecurityContext securityContext = oidcHttpFacade.getSecurityContext();

    if (securityContext == null) {
        return null;
    }

    if (source.endsWith("access_token")) {
        return Arrays.asList(securityContext.getTokenString());
    }

    if (source.endsWith("id_token")) {
        return Arrays.asList(securityContext.getIdTokenString());
    }

    JsonNode jsonNode;

    if (source.startsWith("access_token[")) {
        jsonNode = JsonSerialization.mapper.valueToTree(securityContext.getToken());
    } else if (source.startsWith("id_token[")) {
        jsonNode = JsonSerialization.mapper.valueToTree(securityContext.getIdToken());
    } else {
        throw new RuntimeException("Invalid placeholder [" + placeHolder + "]");
    }

    return JsonUtils.getValues(jsonNode, getParameter(source, "Invalid placeholder [" + placeHolder + "]"));
}
 
Example #13
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleAccessDenied(OIDCHttpFacade facade) {
    String accessDeniedPath = getEnforcerConfig().getOnDenyRedirectTo();
    HttpFacade.Response response = facade.getResponse();

    if (accessDeniedPath != null) {
        response.setStatus(302);
        response.setHeader("Location", accessDeniedPath);
    } else {
        response.sendError(403);
    }
}
 
Example #14
Source File: AbstractPolicyEnforcer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Map<String, List<String>> resolveClaims(PathConfig pathConfig, OIDCHttpFacade httpFacade) {
    Map<String, List<String>> claims = new HashMap<>();

    resolveClaims(claims, getEnforcerConfig().getClaimInformationPointConfig(), httpFacade);
    resolveClaims(claims, pathConfig.getClaimInformationPointConfig(), httpFacade);

    return claims;
}
 
Example #15
Source File: KeycloakAdapterPolicyEnforcer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isAuthorized(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, AccessToken accessToken, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) {
    AccessToken original = accessToken;

    if (super.isAuthorized(pathConfig, methodConfig, accessToken, httpFacade, claims)) {
        return true;
    }

    accessToken = requestAuthorizationToken(pathConfig, methodConfig, httpFacade, claims);

    if (accessToken == null) {
        return false;
    }

    AccessToken.Authorization authorization = original.getAuthorization();

    if (authorization == null) {
        authorization = new AccessToken.Authorization();
        authorization.setPermissions(new ArrayList<Permission>());
    }

    AccessToken.Authorization newAuthorization = accessToken.getAuthorization();

    if (newAuthorization != null) {
        Collection<Permission> grantedPermissions = authorization.getPermissions();
        Collection<Permission> newPermissions = newAuthorization.getPermissions();

        for (Permission newPermission : newPermissions) {
            if (!grantedPermissions.contains(newPermission)) {
                grantedPermissions.add(newPermission);
            }
        }
    }

    original.setAuthorization(authorization);

    return super.isAuthorized(pathConfig, methodConfig, accessToken, httpFacade, claims);
}
 
Example #16
Source File: KeycloakAdapterConfigResolver.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    // Select the deployment using the relative request path
    String path = request.getRelativePath();

    // Try to get the exact match first
    Optional<KeycloakDeployment> dep = Optional.ofNullable(pathDeployments.get(path));

    // If no exact match exists then iterate over the pathDeployments entries
    // and find the first deployment whose entry path is a prefix of the request path
    return dep.orElse(getMatchingPathDeployment(path)
            .orElseThrow(throwException(path)));
}
 
Example #17
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 #18
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 #19
Source File: PolicyEnforcerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnDenyRedirectTo() {
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-on-deny-redirect.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/resourcea");
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);

    assertFalse(context.isGranted());
    TestResponse response = TestResponse.class.cast(httpFacade.getResponse());
    assertEquals(302, response.getStatus());
    List<String> location = response.getHeaders().getOrDefault("Location", Collections.emptyList());
    assertFalse(location.isEmpty());
    assertEquals("/accessDenied", location.get(0));
}
 
Example #20
Source File: ClaimInformationPointProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private HttpFacade createHttpFacade(Map<String, List<String>> headers, InputStream requestBody) {
    return new OIDCHttpFacade() {
        private Request request;

        @Override
        public KeycloakSecurityContext getSecurityContext() {
            AccessToken token = new AccessToken();

            token.subject("sub");
            token.setPreferredUsername("username");
            token.getOtherClaims().put("custom_claim", Arrays.asList("param-other-claims-value1", "param-other-claims-value2"));

            IDToken idToken = new IDToken();

            idToken.subject("sub");
            idToken.setPreferredUsername("username");
            idToken.getOtherClaims().put("custom_claim", Arrays.asList("param-other-claims-value1", "param-other-claims-value2"));

            return new KeycloakSecurityContext("tokenString", token, "idTokenString", idToken);
        }

        @Override
        public Request getRequest() {
            if (request == null) {
                request = createHttpRequest(headers, requestBody);
            }
            return request;
        }

        @Override
        public Response getResponse() {
            return createHttpResponse();
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            return new X509Certificate[0];
        }
    };
}
 
Example #21
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private OIDCHttpFacade createHttpFacade(String path, String method, String token, Map<String, List<String>> headers, Map<String, List<String>> parameters, InputStream requestBody) {
    return new OIDCHttpFacade() {
        Request request;
        Response response;

        @Override
        public KeycloakSecurityContext getSecurityContext() {
            AccessToken accessToken;
            try {
                accessToken = new JWSInput(token).readJsonContent(AccessToken.class);
            } catch (JWSInputException cause) {
                throw new RuntimeException(cause);
            }
            return new KeycloakSecurityContext(token, accessToken, null, null);
        }

        @Override
        public Request getRequest() {
            if (request == null) {
                request = createHttpRequest(path, method, headers, parameters, requestBody);
            }
            return request;
        }

        @Override
        public Response getResponse() {
            if (response == null) {
                response = createHttpResponse(headers);
            }
            return response;
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            return new X509Certificate[0];
        }
    };
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
Source File: PathBasedKeycloakConfigResolver.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
    String webContext = getDeploymentKeyForURI(request);

    return getOrCreateDeployment(webContext);
}