Search in sources :

Example 1 with Authorization

use of org.keycloak.representations.AccessToken.Authorization in project keycloak by keycloak.

the class AuthorizationTokenService method resolvePreviousGrantedPermissions.

private void resolvePreviousGrantedPermissions(PermissionTicketToken ticket, KeycloakAuthorizationRequest request, ResourceServer resourceServer, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, ScopeStore scopeStore, AtomicInteger limit) {
    AccessToken rpt = request.getRpt();
    if (rpt != null && rpt.isActive()) {
        Authorization authorizationData = rpt.getAuthorization();
        if (authorizationData != null) {
            Collection<Permission> permissions = authorizationData.getPermissions();
            if (permissions != null) {
                for (Permission grantedPermission : permissions) {
                    if (limit != null && limit.get() <= 0) {
                        break;
                    }
                    Resource resource = resourceStore.findById(grantedPermission.getResourceId(), ticket.getIssuedFor());
                    if (resource != null) {
                        ResourcePermission permission = permissionsToEvaluate.get(resource.getId());
                        if (permission == null) {
                            permission = new ResourcePermission(resource, new ArrayList<>(), resourceServer, grantedPermission.getClaims());
                            permissionsToEvaluate.put(resource.getId(), permission);
                            if (limit != null) {
                                limit.decrementAndGet();
                            }
                        } else {
                            if (grantedPermission.getClaims() != null) {
                                for (Entry<String, Set<String>> entry : grantedPermission.getClaims().entrySet()) {
                                    Set<String> claims = permission.getClaims().get(entry.getKey());
                                    if (claims != null) {
                                        claims.addAll(entry.getValue());
                                    }
                                }
                            }
                        }
                        for (String scopeName : grantedPermission.getScopes()) {
                            Scope scope = scopeStore.findByName(scopeName, resourceServer.getId());
                            if (scope != null) {
                                if (!permission.getScopes().contains(scope)) {
                                    permission.getScopes().add(scope);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) Set(java.util.Set) HashSet(java.util.HashSet) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 2 with Authorization

use of org.keycloak.representations.AccessToken.Authorization in project keycloak by keycloak.

the class RPTIntrospectionProvider method introspect.

@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);
    }
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) AccessToken(org.keycloak.representations.AccessToken) Collection(java.util.Collection)

Example 3 with Authorization

use of org.keycloak.representations.AccessToken.Authorization in project keycloak by keycloak.

the class EntitlementAPITest method testObtainAllEntitlementsWithLimit.

@Test
public void testObtainAllEntitlementsWithLimit() throws Exception {
    org.keycloak.authorization.client.resource.AuthorizationResource authorizationResource = getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization("marta", "password");
    AuthorizationResponse response = authorizationResource.authorize();
    AccessToken accessToken = toAccessToken(response.getToken());
    Authorization authorization = accessToken.getAuthorization();
    assertTrue(authorization.getPermissions().size() >= 20);
    AuthorizationRequest request = new AuthorizationRequest();
    Metadata metadata = new Metadata();
    metadata.setLimit(10);
    request.setMetadata(metadata);
    response = authorizationResource.authorize(request);
    accessToken = toAccessToken(response.getToken());
    authorization = accessToken.getAuthorization();
    assertEquals(10, authorization.getPermissions().size());
    metadata.setLimit(1);
    request.setMetadata(metadata);
    response = authorizationResource.authorize(request);
    accessToken = toAccessToken(response.getToken());
    authorization = accessToken.getAuthorization();
    assertEquals(1, authorization.getPermissions().size());
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) AccessToken(org.keycloak.representations.AccessToken) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 4 with Authorization

use of org.keycloak.representations.AccessToken.Authorization in project keycloak by keycloak.

the class EntitlementAPITest method testPermissionOrder.

@Test
public void testPermissionOrder() throws Exception {
    ClientResource client = getClient(getRealm(), RESOURCE_SERVER_TEST);
    AuthorizationResource authorization = client.authorization();
    JSPolicyRepresentation policy = new JSPolicyRepresentation();
    policy.setName(KeycloakModelUtils.generateId());
    policy.setCode("$evaluation.grant();");
    authorization.policies().js().create(policy).close();
    ResourceRepresentation resource = new ResourceRepresentation();
    resource.setName("my_resource");
    resource.addScope("entity:read");
    try (Response response = authorization.resources().create(resource)) {
        resource = response.readEntity(ResourceRepresentation.class);
    }
    ScopeRepresentation featureAccessScope = new ScopeRepresentation("feature:access");
    authorization.scopes().create(featureAccessScope);
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addPolicy(policy.getName());
    permission.addResource(resource.getId());
    authorization.permissions().resource().create(permission).close();
    ScopePermissionRepresentation scopePermission = new ScopePermissionRepresentation();
    scopePermission.setName(KeycloakModelUtils.generateId());
    scopePermission.addPolicy(policy.getName());
    scopePermission.addScope(featureAccessScope.getName());
    authorization.permissions().scope().create(scopePermission).close();
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(null, "entity:read");
    request.addPermission(null, "feature:access");
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationResponse response = authzClient.authorization().authorize(request);
    AccessToken token = toAccessToken(response.getToken());
    Authorization result = token.getAuthorization();
    assertEquals(2, result.getPermissions().size());
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() == null && p.getScopes().contains(featureAccessScope.getName())));
    String resourceId = resource.getId();
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() != null && p.getResourceId().equals(resourceId) && p.getScopes().contains("entity:read")));
    request = new AuthorizationRequest();
    request.addPermission(null, "feature:access");
    request.addPermission(null, "entity:read");
    response = authzClient.authorization().authorize(request);
    token = toAccessToken(response.getToken());
    result = token.getAuthorization();
    assertEquals(2, result.getPermissions().size());
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() == null && p.getScopes().contains(featureAccessScope.getName())));
    assertTrue(result.getPermissions().stream().anyMatch(p -> p.getResourceId() != null && p.getResourceId().equals(resourceId) && p.getScopes().contains("entity:read")));
}
Also used : RealmEventsConfigRepresentation(org.keycloak.representations.idm.RealmEventsConfigRepresentation) TestApplicationResourceUrls(org.keycloak.testsuite.client.resources.TestApplicationResourceUrls) CoreMatchers.hasItem(org.hamcrest.CoreMatchers.hasItem) Arrays(java.util.Arrays) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) AssertEvents(org.keycloak.testsuite.AssertEvents) AuthzClient(org.keycloak.authorization.client.AuthzClient) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Assert.assertThat(org.junit.Assert.assertThat) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Configuration(org.keycloak.authorization.client.Configuration) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) After(org.junit.After) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) Assert.fail(org.junit.Assert.fail) ClientResource(org.keycloak.admin.client.resource.ClientResource) RealmResource(org.keycloak.admin.client.resource.RealmResource) Collection(java.util.Collection) RolesBuilder(org.keycloak.testsuite.util.RolesBuilder) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) RoleBuilder(org.keycloak.testsuite.util.RoleBuilder) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) List(java.util.List) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) Response(javax.ws.rs.core.Response) Assert.assertFalse(org.junit.Assert.assertFalse) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) NotNull(org.jetbrains.annotations.NotNull) HttpClients(org.apache.http.impl.client.HttpClients) OAuth2Constants(org.keycloak.OAuth2Constants) HardcodedClaim(org.keycloak.protocol.oidc.mappers.HardcodedClaim) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Permission(org.keycloak.representations.idm.authorization.Permission) ResourceResource(org.keycloak.admin.client.resource.ResourceResource) HashMap(java.util.HashMap) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) HttpResponseException(org.keycloak.authorization.client.util.HttpResponseException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ScopePermissionsResource(org.keycloak.admin.client.resource.ScopePermissionsResource) RealmBuilder(org.keycloak.testsuite.util.RealmBuilder) HttpClient(org.apache.http.client.HttpClient) AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) UserBuilder(org.keycloak.testsuite.util.UserBuilder) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) ArquillianResource(org.jboss.arquillian.test.api.ArquillianResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthServer(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude.AuthServer) ContainerController(org.jboss.arquillian.container.test.api.ContainerController) ExpectedException(org.junit.rules.ExpectedException) Base64Url(org.keycloak.common.util.Base64Url) Before(org.junit.Before) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) OIDCAttributeMapperHelper(org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper) Authorization(org.keycloak.representations.AccessToken.Authorization) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) IOException(java.io.IOException) Test(org.junit.Test) EventType(org.keycloak.events.EventType) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) JsonSerialization(org.keycloak.util.JsonSerialization) Assert.assertNull(org.junit.Assert.assertNull) AssertEvents.isUUID(org.keycloak.testsuite.AssertEvents.isUUID) Rule(org.junit.Rule) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) ClientBuilder(org.keycloak.testsuite.util.ClientBuilder) Assert.assertEquals(org.junit.Assert.assertEquals) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) TokenIntrospectionResponse(org.keycloak.authorization.client.representation.TokenIntrospectionResponse) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) Authorization(org.keycloak.representations.AccessToken.Authorization) AuthzClient(org.keycloak.authorization.client.AuthzClient) AccessToken(org.keycloak.representations.AccessToken) ClientResource(org.keycloak.admin.client.resource.ClientResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) Test(org.junit.Test)

Example 5 with Authorization

use of org.keycloak.representations.AccessToken.Authorization in project keycloak by keycloak.

the class EntitlementAPITest method assertResponse.

private void assertResponse(Metadata metadata, Supplier<AuthorizationResponse> responseSupplier) {
    AccessToken.Authorization authorization = toAccessToken(responseSupplier.get().getToken()).getAuthorization();
    Collection<Permission> permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertFalse(permissions.isEmpty());
    for (Permission permission : permissions) {
        if (metadata.getIncludeResourceName()) {
            assertNotNull(permission.getResourceName());
        } else {
            assertNull(permission.getResourceName());
        }
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) Authorization(org.keycloak.representations.AccessToken.Authorization) Permission(org.keycloak.representations.idm.authorization.Permission)

Aggregations

Authorization (org.keycloak.representations.AccessToken.Authorization)15 AccessToken (org.keycloak.representations.AccessToken)14 Permission (org.keycloak.representations.idm.authorization.Permission)11 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)10 ArrayList (java.util.ArrayList)8 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)8 HashSet (java.util.HashSet)6 Set (java.util.Set)6 Test (org.junit.Test)6 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)5 ClientResource (org.keycloak.admin.client.resource.ClientResource)5 AuthzClient (org.keycloak.authorization.client.AuthzClient)5 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)5 Response (javax.ws.rs.core.Response)4 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)4 Collection (java.util.Collection)3 OAuthClient (org.keycloak.testsuite.util.OAuthClient)3 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 List (java.util.List)2