Java Code Examples for org.keycloak.representations.AccessToken#getAuthorization()
The following examples show how to use
org.keycloak.representations.AccessToken#getAuthorization() .
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: RptStore.java From devconf2019-authz with Apache License 2.0 | 6 votes |
public boolean hasPermission(AccessToken rpt, String resourceName, String scopeName) { if (rpt==null || rpt.getAuthorization() == null) { return false; } AccessToken.Authorization authorization = rpt.getAuthorization(); for (Permission permission : authorization.getPermissions()) { if (resourceName.equalsIgnoreCase(permission.getResourceName()) || resourceName.equalsIgnoreCase(permission.getResourceId())) { if (scopeName == null) { return true; } if (permission.getScopes().contains(scopeName)) { return true; } } } return false; }
Example 2
Source File: EntitlementAPITest.java From keycloak with Apache License 2.0 | 6 votes |
private boolean hasPermission(String userName, String password, String resourceId, String... scopeIds) throws Exception { String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", userName, password).getAccessToken(); AuthorizationResponse response = getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(accessToken).authorize(new AuthorizationRequest()); AccessToken rpt = toAccessToken(response.getToken()); Authorization authz = rpt.getAuthorization(); Collection<Permission> permissions = authz.getPermissions(); assertNotNull(permissions); assertFalse(permissions.isEmpty()); for (Permission grantedPermission : permissions) { if (grantedPermission.getResourceId().equals(resourceId)) { return scopeIds == null || scopeIds.length == 0 || grantedPermission.getScopes().containsAll(Arrays.asList(scopeIds)); } } return false; }
Example 3
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testObtainRptWithClientCredentials() throws Exception { AuthorizationResponse response = authorize("Resource A", new String[] {"ScopeA", "ScopeB"}); String rpt = response.getToken(); assertNotNull(rpt); assertFalse(response.isUpgraded()); AccessToken accessToken = toAccessToken(rpt); AccessToken.Authorization authorization = accessToken.getAuthorization(); assertNotNull(authorization); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); }
Example 4
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testObtainRptUsingAccessToken() throws Exception { AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password"); AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB")); String rpt = response.getToken(); assertNotNull(rpt); assertFalse(response.isUpgraded()); AccessToken accessToken = toAccessToken(rpt); AccessToken.Authorization authorization = accessToken.getAuthorization(); assertNotNull(authorization); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); }
Example 5
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testObtainRptWithIDToken() throws Exception { String idToken = getIdToken("marta", "password"); AuthorizationResponse response = authorize("Resource A", new String[] {"ScopeA", "ScopeB"}, idToken, "http://openid.net/specs/openid-connect-core-1_0.html#IDToken"); String rpt = response.getToken(); assertNotNull(rpt); assertFalse(response.isUpgraded()); AccessToken accessToken = toAccessToken(rpt); AccessToken.Authorization authorization = accessToken.getAuthorization(); assertNotNull(authorization); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); }
Example 6
Source File: AuthorizationTokenService.java From keycloak with Apache License 2.0 | 6 votes |
private boolean isUpgraded(AuthorizationRequest request, Authorization authorization) { AccessToken previousRpt = request.getRpt(); if (previousRpt == null) { return false; } Authorization previousAuthorization = previousRpt.getAuthorization(); if (previousAuthorization != null) { Collection<Permission> previousPermissions = previousAuthorization.getPermissions(); if (previousPermissions != null) { for (Permission previousPermission : previousPermissions) { if (!authorization.getPermissions().contains(previousPermission)) { return false; } } } } return true; }
Example 7
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testObtainRptWithClientAdditionalScopes() throws Exception { AuthorizationResponse response = authorize("marta", "password", "Resource A", new String[] {"ScopeA", "ScopeB"}, new String[] {"ScopeC"}); AccessToken accessToken = toAccessToken(response.getToken()); AccessToken.Authorization authorization = accessToken.getAuthorization(); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB", "ScopeC"); assertTrue(permissions.isEmpty()); }
Example 8
Source File: KeycloakAdapterPolicyEnforcer.java From keycloak with Apache License 2.0 | 5 votes |
@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 9
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test public void testTokenIntrospect() throws Exception { AuthzClient authzClient = getAuthzClient(); AccessTokenResponse accessTokenResponse = authzClient.obtainAccessToken("marta", "password"); AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB")); String rpt = response.getToken(); assertNotNull(rpt); assertFalse(response.isUpgraded()); AccessToken accessToken = toAccessToken(rpt); AccessToken.Authorization authorization = accessToken.getAuthorization(); assertNotNull(authorization); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); TokenIntrospectionResponse introspectionResponse = authzClient.protection().introspectRequestingPartyToken(rpt); assertNotNull(introspectionResponse); assertNotNull(introspectionResponse.getPermissions()); oauth.realm("authz-test"); String introspectHttpResponse = oauth.introspectTokenWithClientCredential("resource-server-test", "secret", "requesting_party_token", rpt); Map jsonNode = JsonSerialization.readValue(introspectHttpResponse, Map.class); assertEquals(true, jsonNode.get("active")); Collection permissionClaims = (Collection) jsonNode.get("permissions"); assertNotNull(permissionClaims); assertEquals(1, permissionClaims.size()); Map<String, Object> claim = (Map) permissionClaims.iterator().next(); assertThat(claim.keySet(), containsInAnyOrder("resource_id", "rsname", "resource_scopes", "scopes", "rsid")); assertThat(claim.get("rsname"), equalTo("Resource A")); ResourceRepresentation resourceRep = authzClient.protection().resource().findByName("Resource A"); assertThat(claim.get("rsid"), equalTo(resourceRep.getId())); assertThat(claim.get("resource_id"), equalTo(resourceRep.getId())); assertThat((Collection<String>) claim.get("resource_scopes"), containsInAnyOrder("ScopeA", "ScopeB")); assertThat((Collection<String>) claim.get("scopes"), containsInAnyOrder("ScopeA", "ScopeB")); }
Example 10
Source File: RPTIntrospectionProvider.java From keycloak with Apache License 2.0 | 4 votes |
@Override public Response introspect(String token) { LOGGER.debug("Introspecting requesting party token"); try { AccessToken accessToken = verifyAccessToken(token); ObjectNode tokenMetadata; if (accessToken != null) { AccessToken metadata = new AccessToken(); metadata.id(accessToken.getId()); metadata.setAcr(accessToken.getAcr()); metadata.type(accessToken.getType()); metadata.expiration(accessToken.getExpiration()); metadata.issuedAt(accessToken.getIssuedAt()); metadata.audience(accessToken.getAudience()); metadata.notBefore(accessToken.getNotBefore()); metadata.setRealmAccess(null); metadata.setResourceAccess(null); tokenMetadata = JsonSerialization.createObjectNode(metadata); Authorization authorization = accessToken.getAuthorization(); if (authorization != null) { Collection permissions; if (authorization.getPermissions() != null) { permissions = authorization.getPermissions().stream().map(UmaPermissionRepresentation::new).collect(Collectors.toSet()); } else { permissions = Collections.emptyList(); } tokenMetadata.putPOJO("permissions", permissions); } } else { tokenMetadata = JsonSerialization.createObjectNode(); } tokenMetadata.put("active", accessToken != null); return Response.ok(JsonSerialization.writeValueAsBytes(tokenMetadata)).type(MediaType.APPLICATION_JSON_TYPE).build(); } catch (Exception e) { throw new RuntimeException("Error creating token introspection response.", e); } }
Example 11
Source File: KeycloakAdapterPolicyEnforcer.java From keycloak with Apache License 2.0 | 4 votes |
private AccessToken requestAuthorizationToken(PathConfig pathConfig, PolicyEnforcerConfig.MethodConfig methodConfig, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) { if (getEnforcerConfig().getUserManagedAccess() != null) { return null; } try { KeycloakSecurityContext securityContext = httpFacade.getSecurityContext(); String accessTokenString = securityContext.getTokenString(); KeycloakDeployment deployment = getPolicyEnforcer().getDeployment(); AccessToken accessToken = securityContext.getToken(); AuthorizationRequest authzRequest = new AuthorizationRequest(); if (isBearerAuthorization(httpFacade) || accessToken.getAuthorization() != null) { authzRequest.addPermission(pathConfig.getId(), methodConfig.getScopes()); } if (!claims.isEmpty()) { authzRequest.setClaimTokenFormat("urn:ietf:params:oauth:token-type:jwt"); authzRequest.setClaimToken(Base64.encodeBytes(JsonSerialization.writeValueAsBytes(claims))); } if (accessToken.getAuthorization() != null) { authzRequest.setRpt(accessTokenString); } LOGGER.debug("Obtaining authorization for authenticated user."); AuthorizationResponse authzResponse; if (isBearerAuthorization(httpFacade)) { authzRequest.setSubjectToken(accessTokenString); authzResponse = getAuthzClient().authorization().authorize(authzRequest); } else { authzResponse = getAuthzClient().authorization(accessTokenString).authorize(authzRequest); } if (authzResponse != null) { return AdapterTokenVerifier.verifyToken(authzResponse.getToken(), deployment); } } catch (AuthorizationDeniedException ignore) { LOGGER.debug("Authorization denied", ignore); } catch (Exception e) { LOGGER.debug("Authorization failed", e); } return null; }
Example 12
Source File: AbstractPolicyEnforcer.java From keycloak with Apache License 2.0 | 4 votes |
protected boolean isAuthorized(PathConfig actualPathConfig, MethodConfig methodConfig, AccessToken accessToken, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) { Request request = httpFacade.getRequest(); if (isDefaultAccessDeniedUri(request)) { return true; } Authorization authorization = accessToken.getAuthorization(); if (authorization == null) { return false; } boolean hasPermission = false; Collection<Permission> grantedPermissions = authorization.getPermissions(); for (Permission permission : grantedPermissions) { if (permission.getResourceId() != null) { if (isResourcePermission(actualPathConfig, permission)) { hasPermission = true; if (actualPathConfig.isInstance() && !matchResourcePermission(actualPathConfig, permission)) { continue; } if (hasResourceScopePermission(methodConfig, permission)) { if (LOGGER.isDebugEnabled()) { LOGGER.debugf("Authorization GRANTED for path [%s]. Permissions [%s].", actualPathConfig, grantedPermissions); } if (HTTP_METHOD_DELETE.equalsIgnoreCase(request.getMethod()) && actualPathConfig.isInstance()) { policyEnforcer.getPathMatcher().removeFromCache(getPath(request)); } return hasValidClaims(permission, claims); } } } else { if (hasResourceScopePermission(methodConfig, permission)) { hasPermission = true; return true; } } } if (!hasPermission && EnforcementMode.PERMISSIVE.equals(actualPathConfig.getEnforcementMode())) { return true; } if (LOGGER.isDebugEnabled()) { LOGGER.debugf("Authorization FAILED for path [%s]. Not enough permissions [%s].", actualPathConfig, grantedPermissions); } return false; }
Example 13
Source File: UmaGrantTypeTest.java From keycloak with Apache License 2.0 | 2 votes |
@Test public void testRefreshRpt() { AccessTokenResponse accessTokenResponse = getAuthzClient().obtainAccessToken("marta", "password"); AuthorizationResponse response = authorize(null, null, null, null, accessTokenResponse.getToken(), null, null, new PermissionRequest("Resource A", "ScopeA", "ScopeB")); String rpt = response.getToken(); assertNotNull(rpt); AccessToken accessToken = toAccessToken(rpt); AccessToken.Authorization authorization = accessToken.getAuthorization(); assertNotNull(authorization); Collection<Permission> permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); String refreshToken = response.getRefreshToken(); assertNotNull(refreshToken); AccessToken refreshTokenToken = toAccessToken(refreshToken); assertNotNull(refreshTokenToken.getAuthorization()); Client client = ClientBuilder.newClient(); UriBuilder builder = UriBuilder.fromUri(AUTH_SERVER_ROOT); URI uri = OIDCLoginProtocolService.tokenUrl(builder).build(REALM_NAME); WebTarget target = client.target(uri); Form parameters = new Form(); parameters.param("grant_type", OAuth2Constants.REFRESH_TOKEN); parameters.param(OAuth2Constants.REFRESH_TOKEN, refreshToken); AccessTokenResponse refreshTokenResponse = target.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")) .post(Entity.form(parameters)).readEntity(AccessTokenResponse.class); assertNotNull(refreshTokenResponse.getToken()); refreshToken = refreshTokenResponse.getRefreshToken(); refreshTokenToken = toAccessToken(refreshToken); assertNotNull(refreshTokenToken.getAuthorization()); AccessToken refreshedToken = toAccessToken(rpt); authorization = refreshedToken.getAuthorization(); assertNotNull(authorization); permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); refreshTokenResponse = target.request() .header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("resource-server-test", "secret")) .post(Entity.form(parameters)).readEntity(AccessTokenResponse.class); assertNotNull(refreshTokenResponse.getToken()); refreshToken = refreshTokenResponse.getRefreshToken(); refreshTokenToken = toAccessToken(refreshToken); assertNotNull(refreshTokenToken.getAuthorization()); refreshedToken = toAccessToken(rpt); authorization = refreshedToken.getAuthorization(); assertNotNull(authorization); permissions = authorization.getPermissions(); assertNotNull(permissions); assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB"); assertTrue(permissions.isEmpty()); }