Skip to content

Instantly share code, notes, and snippets.

@rkbalgi
Created October 6, 2018 11:04
Show Gist options
  • Save rkbalgi/ae1169e047fa88460791434beaafeb74 to your computer and use it in GitHub Desktop.
Save rkbalgi/ae1169e047fa88460791434beaafeb74 to your computer and use it in GitHub Desktop.
Check permissions of a user in Keycloak with Java API
AccessTokenResponse token = authzClient
.obtainAccessToken(userName, password);
final AuthorizationRequest authReq = new AuthorizationRequest();
//checking for a specific permission
authReq.setMetadata(new Metadata());
authReq.getMetadata().setResponseMode("decision");
authReq.addPermission("payroll", "write");
AuthorizationResponse authResponse = null;
try {
authResponse = authzClient
.authorization(token.getToken()).authorize(authReq);
LOG.warn("Permission granted .. for ...");
authReq.getPermissions().getPermissions().forEach(p -> {
LOG.debug(p.getResourceId() + " with scopes - " + p.getScopes());
});
} catch (AuthorizationDeniedException e) {
LOG.warn("Permission denied .. for ");
authReq.getPermissions().getPermissions().forEach(p -> {
LOG.debug(p.getResourceId() + " with scopes - " + p.getScopes());
});
return JsonNodeFactory.instance.objectNode().put("token", token.getToken());
}
LOG.info("RPT = " + authResponse.getToken());
TokenIntrospectionResponse introspectionResponse = authzClient
.protection()
.introspectRequestingPartyToken(authResponse.getToken());
introspectionResponse.getPermissions().stream().forEach(p -> {
LOG.debug(p.getResourceName() + "-- scopes: " + p.getScopes() + " -" + p.getResourceId());
});
@rkbalgi
Copy link
Author

rkbalgi commented Oct 6, 2018

If you're using 4.4 and wondering if you have to use application.yml or keycloak.json then the answer is "use application.yml only". Below is a sample -

server:
 port: 8181

logging.level.org.keycloak: trace
logging.level.org.springframework.security: trace

keycloak:
  enable-basic-auth: false
  realm: demo
  auth-server-url: http://localhost:8080/auth
  ssl-required: none
  resource: spring-demo-app
  use-resource-role-mappings: false
  bearer-only: true
  credentials:
    secret: xxxxxx-secret-secret-998x7x61

  policy-enforcer-config:
    enforcement-mode: ENFORCING
    paths:
      - name: "login"
        path: "/token/generate"
        enforcement-mode: DISABLED


Please note that the last part DISABLES the URI (i.e. unprotected URL's)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment