### Build the Project Source: https://github.com/keycloak/keycloak-client/blob/main/README.md Use this command to clean and install the project, skipping tests. This is a common command for building Maven projects. ```bash mvn clean install -DskipTests=true ``` -------------------------------- ### RBAC Role Check Example Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-authorization-context.adoc This example demonstrates a traditional Role-Based Access Control (RBAC) check using User.hasRole. It is provided for comparison with Keycloak's authorization context. ```java if (User.hasRole('user')) { // user can access the Project Resource } if (User.hasRole('admin')) { // user can access administration resources } if (User.hasRole('project-manager')) { // user can create new projects } ``` -------------------------------- ### Run Testsuite Source: https://github.com/keycloak/keycloak-client/blob/main/README.md Navigate to the testsuite directory and run 'mvn clean install' to execute the test suite. This command builds and tests the testsuite module. ```bash cd testsuite mvn clean install ``` -------------------------------- ### Example ClaimInformationPointProvider Implementation Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-claim-information-point.adoc Implement the ClaimInformationPointProvider interface to define custom logic for resolving claims. The constructor receives configuration specific to this provider. ```java public class MyClaimInformationPointProvider implements ClaimInformationPointProvider { private final Map config; public MyClaimInformationPointProvider(Map config) { this.config = config; } @Override public Map> resolve(HttpFacade httpFacade) { Map> claims = new HashMap<>(); // put whatever claim you want into the map return claims; } } ``` -------------------------------- ### Instantiate Keycloak with Custom JacksonProvider Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/admin-client.adoc Example of creating the Keycloak client instance when providing a custom JacksonProvider. Ensure your custom provider configures the ObjectMapper correctly. ```java Keycloak.getInstance( "http://localhost:8080", "master", "admin", "admin", "admin-cli", null, null, new MyCustomJacksonProvider() ); ``` -------------------------------- ### Get Master Realm Details with Java Client Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/admin-client.adoc Instantiate the Keycloak admin client and retrieve the representation of the master realm. ```java import org.keycloak.admin.client.Keycloak; import org.keycloak.representations.idm.RealmRepresentation; ... Keycloak keycloak = Keycloak.getInstance( "http://localhost:8080", "master", "admin", "password", "admin-cli"); RealmRepresentation realm = keycloak.realm("master").toRepresentation(); ``` -------------------------------- ### Claim Information Provider SPI Factory Example Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-claim-information-point.adoc Implement a custom Claim Information Point Provider by extending the `ClaimInformationPointProviderFactory` interface. This allows for custom claim resolution logic beyond built-in providers. ```java public class MyClaimInformationPointProviderFactory implements ClaimInformationPointProviderFactory { @Override public String getName() { return "my-claims"; } @Override public void init(PolicyEnforcer policyEnforcer) { } @Override public MyClaimInformationPointProvider create(Map config) { return new MyClaimInformationPointProvider(config); } } ``` -------------------------------- ### Run Testsuite with Remote Keycloak Server Source: https://github.com/keycloak/keycloak-client/blob/main/README.md Execute the testsuite using a remote Keycloak server by setting the 'keycloak.lifecycle' property to 'remote'. This avoids starting a new Keycloak server instance. ```bash mvn clean install -Dkeycloak.lifecycle=remote ``` -------------------------------- ### Obtain AuthorizationContext from HttpServletRequest Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-authorization-context.adoc Retrieve the AuthorizationContext from the HttpServletRequest attributes. This is the starting point for checking permissions. ```java HttpServletRequest request = // obtain javax.servlet.http.HttpServletRequest AuthorizationContext authzContext = (AuthorizationContext) request.getAttribute(AuthorizationContext.class.getName()); ``` -------------------------------- ### Create AuthzClient Instance Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Instantiates the AuthzClient using the configuration found in keycloak.json located in the classpath. ```java // create a new instance based on the configuration defined in a keycloak.json located in your classpath AuthzClient authzClient = AuthzClient.create(); ``` -------------------------------- ### Create a Resource using Protection API Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Creates a new resource on the Keycloak server using the protection API. It defines the resource's name, type, and associated scopes before creation. ```java // create a new instance based on the configuration defined in keycloak.json AuthzClient authzClient = AuthzClient.create(); // create a new resource representation with the information we want ResourceRepresentation newResource = new ResourceRepresentation(); newResource.setName("New Resource"); newResource.setType("urn:hello-world-authz:resources:example"); newResource.addScope(new ScopeRepresentation("urn:hello-world-authz:scopes:view")); ProtectedResource resourceClient = authzClient.protection().resource(); ResourceRepresentation existingResource = resourceClient.findByName(newResource.getName()); if (existingResource != null) { resourceClient.delete(existingResource.getId()); } // create the resource on the server ResourceRepresentation response = resourceClient.create(newResource); String resourceId = response.getId(); ``` -------------------------------- ### Manual Path Protection Configuration Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-configuration.adoc Use this JSON configuration to manually define protected paths, HTTP methods, and associated scopes. This is useful when automatic resource discovery is not sufficient. ```json { "enforcement-mode" : "ENFORCING", "paths": [ { "path" : "/users/*", "methods" : [ { "method": "GET", "scopes" : ["urn:app.com:scopes:view"] }, { "method": "POST", "scopes" : ["urn:app.com:scopes:create"] } ] } ] } ``` -------------------------------- ### Configure Truststore for HTTPS Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-https.adoc This JSON configuration snippet is used to enable TLS/HTTPS for the Authorization Client. It specifies the path to the truststore and its password. ```json { "truststore": "path_to_your_trust_store", "truststore-password": "trust_store_password" } ``` -------------------------------- ### Run Testsuite with Specific Keycloak Version Source: https://github.com/keycloak/keycloak-client/blob/main/README.md Override the default Keycloak Docker image version by specifying the 'keycloak.version.docker.image' property. This allows testing against a particular Keycloak server version. ```bash mvn clean install -Dkeycloak.version.docker.image=24.0 ``` -------------------------------- ### Check Scope Permissions Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-authorization-context.adoc Use hasScopePermission to verify if the user has been granted a specific scope, such as the permission to create new projects. This allows for fine-grained access control. ```java if (authzContext.hasScopePermission("urn:project.com:project:create")) { // user can create new projects } ``` -------------------------------- ### Keycloak Authz Client Configuration Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Defines the configuration for the Keycloak Authorization Client in a keycloak.json file. This includes realm, auth-server-url, resource, and credentials. ```json { "realm": "hello-world-authz", "auth-server-url" : "http://localhost:8080", "resource" : "hello-world-authz-service", "credentials": { "secret": "secret" } } ``` -------------------------------- ### Obtain User Entitlements (RPT) Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Requests an RPT (Requesting Party Token) for a user by sending an authorization request to the server. The RPT can then be used to access protected resources. ```java // create a new instance based on the configuration defined in keycloak.json AuthzClient authzClient = AuthzClient.create(); // create an authorization request AuthorizationRequest request = new AuthorizationRequest(); // send the entitlement request to the server in order to // obtain an RPT with all permissions granted to the user AuthorizationResponse response = authzClient.authorization("alice", "alice").authorize(request); String rpt = response.getToken(); System.out.println("You got an RPT: " + rpt); // now you can use the RPT to access protected resources on the resource server ``` -------------------------------- ### Signed JWT Client Authentication Configuration Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Configuration for client authentication using a signed JWT based on RFC7523. Requires a keystore file and associated passwords and alias. ```json "credentials": { "jwt": { "client-keystore-file": "classpath:keystore-client.jks", "client-keystore-type": "JKS", "client-keystore-password": "storepass", "client-key-password": "keypass", "client-key-alias": "clientkey", "token-expiration": 10 } } ``` -------------------------------- ### Obtain User Entitlements for Specific Resources Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Requests an RPT for specific resources by adding permissions to the authorization request. This allows checking access for a defined set of resources and scopes. ```java // create a new instance based on the configuration defined in keycloak.json AuthzClient authzClient = AuthzClient.create(); // create an authorization request AuthorizationRequest request = new AuthorizationRequest(); // add permissions to the request based on the resources and scopes you want to check access request.addPermission("Default Resource"); // send the entitlement request to the server in order to // obtain an RPT with permissions for a single resource AuthorizationResponse response = authzClient.authorization("alice", "alice").authorize(request); String rpt = response.getToken(); System.out.println("You got an RPT: " + rpt); // now you can use the RPT to access protected resources on the resource server ``` -------------------------------- ### Check Resource Permissions Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-authorization-context.adoc Use hasResourcePermission to verify if the user has been granted access to a specific resource. This is useful for controlling access to different parts of your application. ```java if (authzContext.hasResourcePermission("Project Resource")) { // user can access the Project Resource } if (authzContext.hasResourcePermission("Admin Resource")) { // user can access administration resources } ``` -------------------------------- ### Add Keycloak Admin Client Maven Dependency Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/admin-client.adoc Include the keycloak-admin-client library in your Maven project to use the admin client. ```xml org.keycloak keycloak-admin-client ${client_version} ``` -------------------------------- ### Client ID and Client Secret Configuration Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Configuration for client authentication using a client ID and secret, as per OAuth2 specification. This secret must be configured in both the client application and the Keycloak Admin Console. ```json "credentials": { "secret": "19666a4f-32dd-4049-b082-684c74115f28" } ``` -------------------------------- ### Fetching Claims from External HTTP Service Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-claim-information-point.adoc Configure the policy-enforcer to fetch claims from an external HTTP service. Specify the service URL, HTTP method, headers, and parameters, including dynamic claims from the access token. This allows for richer context based on external data. ```json { "paths": [ { "path": "/protected/resource", "claim-information-point": { "http": { "claims": { "claim-a": "/a", "claim-d": "/d", "claim-d0": "/d/0", "claim-d-all": [ "/d/0", "/d/1" ] }, "url": "http://mycompany/claim-provider", "method": "POST", "headers": { "Content-Type": "application/x-www-form-urlencoded", "header-b": [ "header-b-value1", "header-b-value2" ], "Authorization": "Bearer {keycloak.access_token}" }, "parameters": { "param-a": [ "param-a-value1", "param-a-value2" ], "param-subject": "{keycloak.access_token['/sub']}", "param-user-name": "{keycloak.access_token['/preferred_username']}", "param-other-claims": "{keycloak.access_token['/custom_claim']}" } } } } ] } ``` -------------------------------- ### Configure ObjectMapper for Compatibility Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/admin-client.adoc Ensure the ObjectMapper used by the admin client is configured to handle potential differences between client and server representations. This is crucial when providing a custom JacksonProvider. ```java objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ``` -------------------------------- ### Maven Dependency for Keycloak Authz Client Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Add this dependency to your Maven project to include the Keycloak Authorization Client library. ```xml org.keycloak keycloak-authz-client ${client_version} ``` -------------------------------- ### Defining Static Claims Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-claim-information-point.adoc Configure static claims directly within the policy-enforcer configuration. This is useful for providing fixed values or predefined lists of values that do not change based on the request context. ```json { "paths": [ { "path": "/protected/resource", "claim-information-point": { "claims": { "claim-from-static-value": "static value", "claim-from-multiple-static-value": ["static", "value"] } } } ] } ``` -------------------------------- ### Introspect an RPT Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Obtain an RPT and then introspect it to check its active status and granted permissions. Requires an initialized AuthzClient. ```java AuthzClient authzClient = AuthzClient.create(); AuthorizationResponse response = authzClient.authorization("alice", "alice").authorize(); String rpt = response.getToken(); TokenIntrospectionResponse requestingPartyToken = authzClient.protection().introspectRequestingPartyToken(rpt); System.out.println("Token status is: " + requestingPartyToken.getActive()); System.out.println("Permissions granted by the server: "); for (Permission granted : requestingPartyToken.getPermissions()) { System.out.println(granted); } ``` -------------------------------- ### Obtain AuthzClient from AuthorizationContext Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-authorization-context.adoc Retrieve the AuthzClient instance from the ClientAuthorizationContext. This client can be used to interact programmatically with the authorization server. ```java ClientAuthorizationContext clientContext = ClientAuthorizationContext.class.cast(authzContext); AuthzClient authzClient = clientContext.getClient(); ``` -------------------------------- ### Extracting Claims from HTTP Request Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-claim-information-point.adoc Configure claim extraction from various parts of an HTTP request, including parameters, headers, cookies, remote address, method, URI, body, and static values. Use this to enrich access context based on request details. ```json { "paths": [ { "path": "/protected/resource", "claim-information-point": { "claims": { "claim-from-request-parameter": "{request.parameter['a aktivnosti']}", "claim-from-header": "{request.header['b']}", "claim-from-cookie": "{request.cookie['c']}", "claim-from-remoteAddr": "{request.remoteAddr}", "claim-from-method": "{request.method}", "claim-from-uri": "{request.uri}", "claim-from-relativePath": "{request.relativePath}", "claim-from-secure": "{request.secure}", "claim-from-json-body-object": "{request.body['/a/b/c']}", "claim-from-json-body-array": "{request.body['/d/1']}", "claim-from-body": "{request.body}", "claim-from-static-value": "static value", "claim-from-multiple-static-value": ["static", "value"], "param-replace-multiple-placeholder": "Test {keycloak.access_token['/custom_claim/0']} and {request.parameter['a']}" } } } ] } ``` -------------------------------- ### Signed JWT with Client Secret Configuration Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/authz-client.adoc Configuration for client authentication using a signed JWT, but with a client secret instead of a private key. The secret must be configured in both the client application and the Keycloak Admin Console. ```json "credentials": { "secret-jwt": { "secret": "19666a4f-32dd-4049-b082-684c74115f28" } } ``` -------------------------------- ### Keycloak Policy Enforcer Maven Dependency Source: https://github.com/keycloak/keycloak-client/blob/main/docs/guides/securing-apps/partials/policy-enforcer/enforcer-overview.adoc Add this dependency to your Maven project to enable the Keycloak Policy Enforcer for Java applications. ```xml org.keycloak keycloak-policy-enforcer ${client_version} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.