Search in sources :

Example 41 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class UserManagedAccessTest method testUserGrantedAccessConsideredWhenRequestingAuthorizationByResourceName.

@Test
public void testUserGrantedAccessConsideredWhenRequestingAuthorizationByResourceName() throws Exception {
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    resource = addResource("Resource A", "marta", true, "ScopeA", "ScopeB");
    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getId());
    permission.addPolicy("Only Owner Policy");
    getClient(getRealm()).authorization().permissions().resource().create(permission).close();
    try {
        AuthorizationResponse response = authorize("kolo", "password", resource.getId(), new String[] {});
        fail("User should not have access to resource from another user");
    } catch (AuthorizationDeniedException ade) {
    }
    PermissionResource permissionResource = getAuthzClient().protection().permission();
    List<PermissionTicketRepresentation> permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    assertEquals(2, permissionTickets.size());
    for (PermissionTicketRepresentation ticket : permissionTickets) {
        assertFalse(ticket.isGranted());
        ticket.setGranted(true);
        permissionResource.update(ticket);
    }
    permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    assertEquals(2, permissionTickets.size());
    for (PermissionTicketRepresentation ticket : permissionTickets) {
        assertTrue(ticket.isGranted());
    }
    AuthorizationRequest request = new AuthorizationRequest();
    // No resource id used in request, only name
    request.addPermission("Resource A", "ScopeA", "ScopeB");
    List<Permission> permissions = authorize("kolo", "password", request);
    assertEquals(1, permissions.size());
    Permission koloPermission = permissions.get(0);
    assertEquals("Resource A", koloPermission.getResourceName());
    assertTrue(koloPermission.getScopes().containsAll(Arrays.asList("ScopeA", "ScopeB")));
    ResourceRepresentation resourceRep = getAuthzClient().protection().resource().findById(resource.getId());
    resourceRep.setName("Resource A Changed");
    getAuthzClient().protection().resource().update(resourceRep);
    request = new AuthorizationRequest();
    // Try to use the old name
    request.addPermission("Resource A", "ScopeA", "ScopeB");
    try {
        authorize("kolo", "password", request);
        fail("User should not have access to resource from another user");
    } catch (RuntimeException ade) {
        assertTrue(ade.getCause().toString().contains("invalid_resource"));
    }
    request = new AuthorizationRequest();
    request.addPermission(resourceRep.getName(), "ScopeA", "ScopeB");
    permissions = authorize("kolo", "password", request);
    assertEquals(1, permissions.size());
    koloPermission = permissions.get(0);
    assertEquals(resourceRep.getName(), koloPermission.getResourceName());
    assertTrue(koloPermission.getScopes().containsAll(Arrays.asList("ScopeA", "ScopeB")));
}
Also used : AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) PermissionResource(org.keycloak.authorization.client.resource.PermissionResource) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Test(org.junit.Test)

Example 42 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class UserManagedAccessTest method testUserGrantsAccessToResource.

@Test
public void testUserGrantsAccessToResource() throws Exception {
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    resource = addResource("Resource A", "marta", true, "ScopeA", "ScopeB");
    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getId());
    permission.addPolicy("Only Owner Policy");
    ClientResource client = getClient(getRealm());
    client.authorization().permissions().resource().create(permission).close();
    AuthorizationResponse response = authorize("marta", "password", "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());
    getTestContext().getTestingClient().testing().clearEventQueue();
    try {
        response = authorize("kolo", "password", resource.getId(), new String[] {});
        fail("User should not have access to resource from another user");
    } catch (AuthorizationDeniedException ade) {
    }
    String realmId = getRealm().toRepresentation().getId();
    String clientId = client.toRepresentation().getClientId();
    events.expectLogin().realm(realmId).client(clientId).user(isUUID()).clearDetails().assertEvent();
    events.expectLogin().realm(realmId).client(clientId).user(isUUID()).clearDetails().assertEvent();
    events.expect(EventType.PERMISSION_TOKEN_ERROR).realm(realmId).client(clientId).user(isUUID()).session((String) null).error("access_denied").detail("reason", "request_submitted").assertEvent();
    PermissionResource permissionResource = getAuthzClient().protection().permission();
    List<PermissionTicketRepresentation> permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    assertEquals(2, permissionTickets.size());
    for (PermissionTicketRepresentation ticket : permissionTickets) {
        assertFalse(ticket.isGranted());
        ticket.setGranted(true);
        permissionResource.update(ticket);
    }
    permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    assertEquals(2, permissionTickets.size());
    for (PermissionTicketRepresentation ticket : permissionTickets) {
        assertTrue(ticket.isGranted());
    }
    getTestContext().getTestingClient().testing().clearEventQueue();
    response = authorize("kolo", "password", resource.getId(), new String[] { "ScopeA", "ScopeB" });
    rpt = response.getToken();
    assertNotNull(rpt);
    assertFalse(response.isUpgraded());
    accessToken = toAccessToken(rpt);
    authorization = accessToken.getAuthorization();
    assertNotNull(authorization);
    permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, resource.getName(), "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
    events.expectLogin().realm(realmId).client(clientId).user(isUUID()).clearDetails().assertEvent();
    events.expectLogin().realm(realmId).client(clientId).user(isUUID()).clearDetails().assertEvent();
    events.expect(EventType.PERMISSION_TOKEN).realm(realmId).client(clientId).user(isUUID()).session((String) null).clearDetails().assertEvent();
}
Also used : AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) PermissionResource(org.keycloak.authorization.client.resource.PermissionResource) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 43 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class UserManagedAccessTest method testPermissiveModePermissions.

@Test
public void testPermissiveModePermissions() throws Exception {
    resource = addResource("Resource A");
    try {
        authorize("kolo", "password", resource.getId(), null);
        fail("Access should be denied, server in enforcing mode");
    } catch (AuthorizationDeniedException ade) {
    }
    AuthorizationResource authorizationResource = getClient(getRealm()).authorization();
    ResourceServerRepresentation settings = authorizationResource.getSettings();
    settings.setPolicyEnforcementMode(PolicyEnforcementMode.PERMISSIVE);
    authorizationResource.update(settings);
    AuthorizationResponse response = authorize("marta", "password", "Resource A", null);
    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");
    assertTrue(permissions.isEmpty());
}
Also used : AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 44 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class AuthorizationTokenService method isUpgraded.

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;
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) AccessToken(org.keycloak.representations.AccessToken) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission)

Example 45 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class AuthorizationTokenService method resolveResourcePermission.

private void resolveResourcePermission(KeycloakAuthorizationRequest request, ResourceServer resourceServer, KeycloakIdentity identity, AuthorizationProvider authorization, StoreFactory storeFactory, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, AtomicInteger limit, Permission permission, Set<Scope> requestedScopesModel, String resourceId) {
    Resource resource;
    if (resourceId.indexOf('-') != -1) {
        resource = resourceStore.findById(resourceId, resourceServer.getId());
    } else {
        resource = null;
    }
    if (resource != null) {
        addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource);
    } else if (resourceId.startsWith("resource-type:")) {
        // only resource types, no resource instances. resource types are owned by the resource server
        String resourceType = resourceId.substring("resource-type:".length());
        resourceStore.findByType(resourceType, resourceServer.getId(), resourceServer.getId(), resource1 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource1));
    } else if (resourceId.startsWith("resource-type-any:")) {
        // any resource with a given type
        String resourceType = resourceId.substring("resource-type-any:".length());
        resourceStore.findByType(resourceType, null, resourceServer.getId(), resource12 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource12));
    } else if (resourceId.startsWith("resource-type-instance:")) {
        // only resource instances with a given type
        String resourceType = resourceId.substring("resource-type-instance:".length());
        resourceStore.findByTypeInstance(resourceType, resourceServer.getId(), resource13 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource13));
    } else if (resourceId.startsWith("resource-type-owner:")) {
        // only resources where the current identity is the owner
        String resourceType = resourceId.substring("resource-type-owner:".length());
        resourceStore.findByType(resourceType, identity.getId(), resourceServer.getId(), resource14 -> addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, resource14));
    } else {
        Resource ownerResource = resourceStore.findByName(resourceId, identity.getId(), resourceServer.getId());
        if (ownerResource != null) {
            permission.setResourceId(ownerResource.getId());
            addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, ownerResource);
        }
        if (!identity.isResourceServer() || !identity.getId().equals(resourceServer.getId())) {
            List<PermissionTicket> tickets = storeFactory.getPermissionTicketStore().findGranted(resourceId, identity.getId(), resourceServer.getId());
            if (!tickets.isEmpty()) {
                List<Scope> scopes = new ArrayList<>();
                Resource grantedResource = null;
                for (PermissionTicket permissionTicket : tickets) {
                    if (grantedResource == null) {
                        grantedResource = permissionTicket.getResource();
                    }
                    scopes.add(permissionTicket.getScope());
                }
                requestedScopesModel.retainAll(scopes);
                ResourcePermission resourcePermission = addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, grantedResource);
                // the permission is explicitly granted by the owner, mark this permission as granted so that we don't run the evaluation engine on it
                resourcePermission.setGranted(true);
            }
            Resource serverResource = resourceStore.findByName(resourceId, resourceServer.getId());
            if (serverResource != null) {
                permission.setResourceId(serverResource.getId());
                addPermission(request, resourceServer, authorization, permissionsToEvaluate, limit, requestedScopesModel, serverResource);
            }
        }
    }
    if (permissionsToEvaluate.isEmpty()) {
        CorsErrorResponseException invalidResourceException = new CorsErrorResponseException(request.getCors(), "invalid_resource", "Resource with id [" + resourceId + "] does not exist.", Status.BAD_REQUEST);
        fireErrorEvent(request.getEvent(), Errors.INVALID_REQUEST, invalidResourceException);
        throw invalidResourceException;
    }
}
Also used : ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Arrays(java.util.Arrays) Tokens(org.keycloak.authorization.util.Tokens) UserSessionProvider(org.keycloak.models.UserSessionProvider) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) BiFunction(java.util.function.BiFunction) Permissions(org.keycloak.authorization.permission.Permissions) PermissionTicketAwareDecisionResultCollector(org.keycloak.authorization.policy.evaluation.PermissionTicketAwareDecisionResultCollector) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) Metadata(org.keycloak.representations.idm.authorization.AuthorizationRequest.Metadata) MediaType(javax.ws.rs.core.MediaType) OAuthErrorException(org.keycloak.OAuthErrorException) AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AccessToken(org.keycloak.representations.AccessToken) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) ClientConnection(org.keycloak.common.ClientConnection) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RealmModel(org.keycloak.models.RealmModel) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) ResourceStore(org.keycloak.authorization.store.ResourceStore) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) Collectors(java.util.stream.Collectors) IDToken(org.keycloak.representations.IDToken) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Objects(java.util.Objects) List(java.util.List) ScopeStore(org.keycloak.authorization.store.ScopeStore) ServiceAccountConstants(org.keycloak.common.constants.ServiceAccountConstants) Response(javax.ws.rs.core.Response) Details(org.keycloak.events.Details) DefaultEvaluationContext(org.keycloak.authorization.common.DefaultEvaluationContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) Entry(java.util.Map.Entry) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) Permission(org.keycloak.representations.idm.authorization.Permission) Logger(org.jboss.logging.Logger) StoreFactory(org.keycloak.authorization.store.StoreFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) RefreshToken(org.keycloak.representations.RefreshToken) TokenManager(org.keycloak.protocol.oidc.TokenManager) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) EventBuilder(org.keycloak.events.EventBuilder) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) Cors(org.keycloak.services.resources.Cors) Status(javax.ws.rs.core.Response.Status) Base64Url(org.keycloak.common.util.Base64Url) ResourceServer(org.keycloak.authorization.model.ResourceServer) Errors(org.keycloak.events.Errors) Authorization(org.keycloak.representations.AccessToken.Authorization) KeycloakSession(org.keycloak.models.KeycloakSession) HttpRequest(org.jboss.resteasy.spi.HttpRequest) UserSessionModel(org.keycloak.models.UserSessionModel) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) JsonSerialization(org.keycloak.util.JsonSerialization) EvaluationContext(org.keycloak.authorization.policy.evaluation.EvaluationContext) ResourceServerStore(org.keycloak.authorization.store.ResourceServerStore) Urls(org.keycloak.services.Urls) AccessTokenResponseBuilder(org.keycloak.protocol.oidc.TokenManager.AccessTokenResponseBuilder) Resource(org.keycloak.authorization.model.Resource) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) Scope(org.keycloak.authorization.model.Scope) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Aggregations

Permission (org.keycloak.representations.idm.authorization.Permission)73 Test (org.junit.Test)50 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)44 AccessToken (org.keycloak.representations.AccessToken)36 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)29 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)27 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)23 AuthzClient (org.keycloak.authorization.client.AuthzClient)22 ClientResource (org.keycloak.admin.client.resource.ClientResource)20 ArrayList (java.util.ArrayList)19 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)15 ScopePermissionRepresentation (org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)14 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)13 Response (javax.ws.rs.core.Response)12 AuthorizationDeniedException (org.keycloak.authorization.client.AuthorizationDeniedException)12 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)12 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)12 PermissionResponse (org.keycloak.representations.idm.authorization.PermissionResponse)12 Authorization (org.keycloak.representations.AccessToken.Authorization)11