Created
October 6, 2018 11:04
-
-
Save rkbalgi/ae1169e047fa88460791434beaafeb74 to your computer and use it in GitHub Desktop.
Check permissions of a user in Keycloak with Java API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
}); |
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
Ref: https://www.keycloak.org/docs/latest/authorization_services/#_service_user_managed_access
(Also, please note "client scopes" may be of special interest, try turning on "Full Scope" for testing).