Search in sources :

Example 36 with ScopeRepresentation

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

the class PermissionsTest method clientAuthorization.

@Test
public void clientAuthorization() {
    ProfileAssume.assumeFeatureEnabled(Profile.Feature.AUTHORIZATION);
    ClientRepresentation newClient = new ClientRepresentation();
    newClient.setClientId("foo-authz");
    adminClient.realms().realm(REALM_NAME).clients().create(newClient);
    ClientRepresentation foo = adminClient.realms().realm(REALM_NAME).clients().findByClientId("foo-authz").get(0);
    invoke(new InvocationWithResponse() {

        public void invoke(RealmResource realm, AtomicReference<Response> response) {
            foo.setServiceAccountsEnabled(true);
            foo.setAuthorizationServicesEnabled(true);
            realm.clients().get(foo.getId()).update(foo);
        }
    }, CLIENT, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            realm.clients().get(foo.getId()).authorization().getSettings();
        }
    }, AUTHORIZATION, false);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            ResourceServerRepresentation settings = authorization.getSettings();
            authorization.update(settings);
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.resources().resources();
        }
    }, AUTHORIZATION, false);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.scopes().scopes();
        }
    }, AUTHORIZATION, false);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.policies().policies();
        }
    }, AUTHORIZATION, false);
    invoke(new InvocationWithResponse() {

        public void invoke(RealmResource realm, AtomicReference<Response> response) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            response.set(authorization.resources().create(new ResourceRepresentation("Test", Collections.emptySet())));
        }
    }, AUTHORIZATION, true);
    invoke(new InvocationWithResponse() {

        public void invoke(RealmResource realm, AtomicReference<Response> response) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            response.set(authorization.scopes().create(new ScopeRepresentation("Test")));
        }
    }, AUTHORIZATION, true);
    invoke(new InvocationWithResponse() {

        public void invoke(RealmResource realm, AtomicReference<Response> response) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            ResourcePermissionRepresentation representation = new ResourcePermissionRepresentation();
            representation.setName("Test PermissionsTest");
            representation.addResource("Default Resource");
            response.set(authorization.permissions().resource().create(representation));
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.resources().resource("nosuch").update(new ResourceRepresentation());
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.scopes().scope("nosuch").update(new ScopeRepresentation());
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.policies().policy("nosuch").update(new PolicyRepresentation());
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.resources().resource("nosuch").remove();
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.scopes().scope("nosuch").remove();
        }
    }, AUTHORIZATION, true);
    invoke(new Invocation() {

        public void invoke(RealmResource realm) {
            AuthorizationResource authorization = realm.clients().get(foo.getId()).authorization();
            authorization.policies().policy("nosuch").remove();
        }
    }, AUTHORIZATION, true);
}
Also used : Response(javax.ws.rs.core.Response) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) ResourceServerRepresentation(org.keycloak.representations.idm.authorization.ResourceServerRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 37 with ScopeRepresentation

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

the class RepresentationToModel method toModel.

public static Resource toModel(ResourceRepresentation resource, ResourceServer resourceServer, AuthorizationProvider authorization) {
    ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
    ResourceOwnerRepresentation owner = resource.getOwner();
    if (owner == null) {
        owner = new ResourceOwnerRepresentation();
        owner.setId(resourceServer.getId());
    }
    String ownerId = owner.getId();
    if (ownerId == null) {
        ownerId = resourceServer.getId();
    }
    if (!resourceServer.getId().equals(ownerId)) {
        RealmModel realm = authorization.getRealm();
        KeycloakSession keycloakSession = authorization.getKeycloakSession();
        UserProvider users = keycloakSession.users();
        UserModel ownerModel = users.getUserById(realm, ownerId);
        if (ownerModel == null) {
            ownerModel = users.getUserByUsername(realm, ownerId);
        }
        if (ownerModel == null) {
            throw new RuntimeException("Owner must be a valid username or user identifier. If the resource server, the client id or null.");
        }
        ownerId = ownerModel.getId();
    }
    Resource existing;
    if (resource.getId() != null) {
        existing = resourceStore.findById(resource.getId(), resourceServer.getId());
    } else {
        existing = resourceStore.findByName(resource.getName(), ownerId, resourceServer.getId());
    }
    if (existing != null) {
        existing.setName(resource.getName());
        existing.setDisplayName(resource.getDisplayName());
        existing.setType(resource.getType());
        existing.updateUris(resource.getUris());
        existing.setIconUri(resource.getIconUri());
        existing.setOwnerManagedAccess(Boolean.TRUE.equals(resource.getOwnerManagedAccess()));
        existing.updateScopes(resource.getScopes().stream().map((ScopeRepresentation scope) -> toModel(scope, resourceServer, authorization, false)).collect(Collectors.toSet()));
        Map<String, List<String>> attributes = resource.getAttributes();
        if (attributes != null) {
            Set<String> existingAttrNames = existing.getAttributes().keySet();
            for (String name : existingAttrNames) {
                if (attributes.containsKey(name)) {
                    existing.setAttribute(name, attributes.get(name));
                    attributes.remove(name);
                } else {
                    existing.removeAttribute(name);
                }
            }
            for (String name : attributes.keySet()) {
                existing.setAttribute(name, attributes.get(name));
            }
        }
        return existing;
    }
    Resource model = resourceStore.create(resource.getId(), resource.getName(), resourceServer, ownerId);
    model.setDisplayName(resource.getDisplayName());
    model.setType(resource.getType());
    model.updateUris(resource.getUris());
    model.setIconUri(resource.getIconUri());
    model.setOwnerManagedAccess(Boolean.TRUE.equals(resource.getOwnerManagedAccess()));
    Set<ScopeRepresentation> scopes = resource.getScopes();
    if (scopes != null) {
        model.updateScopes(scopes.stream().map(scope -> toModel(scope, resourceServer, authorization, false)).collect(Collectors.toSet()));
    }
    Map<String, List<String>> attributes = resource.getAttributes();
    if (attributes != null) {
        for (Entry<String, List<String>> entry : attributes.entrySet()) {
            model.setAttribute(entry.getKey(), entry.getValue());
        }
    }
    resource.setId(model.getId());
    return model;
}
Also used : Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) ResourceOwnerRepresentation(org.keycloak.representations.idm.authorization.ResourceOwnerRepresentation) ArtifactBindingUtils.computeArtifactBindingIdentifierString(org.keycloak.protocol.saml.util.ArtifactBindingUtils.computeArtifactBindingIdentifierString) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) UserProvider(org.keycloak.models.UserProvider) KeycloakSession(org.keycloak.models.KeycloakSession) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList)

Example 38 with ScopeRepresentation

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

the class EntitlementAPITest method testObtainAllEntitlementsForScopeWithDeny.

@Test
public void testObtainAllEntitlementsForScopeWithDeny() 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();
    authorization.scopes().create(new ScopeRepresentation("sensors:view")).close();
    ScopePermissionRepresentation permission = new ScopePermissionRepresentation();
    permission.setName(KeycloakModelUtils.generateId());
    permission.addScope("sensors:view");
    permission.addPolicy(policy.getName());
    authorization.permissions().scope().create(permission).close();
    String accessToken = new OAuthClient().realm("authz-test").clientId(RESOURCE_SERVER_TEST).doGrantAccessTokenRequest("secret", "kolo", "password").getAccessToken();
    AuthzClient authzClient = getAuthzClient(AUTHZ_CLIENT_CONFIG);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(null, "sensors:view");
    AuthorizationResponse response = authzClient.authorization(accessToken).authorize(request);
    assertNotNull(response.getToken());
    Collection<Permission> permissions = toAccessToken(response.getToken()).getAuthorization().getPermissions();
    assertEquals(1, permissions.size());
    for (Permission grantedPermission : permissions) {
        assertNull(grantedPermission.getResourceId());
        assertEquals(1, grantedPermission.getScopes().size());
        assertTrue(grantedPermission.getScopes().containsAll(Arrays.asList("sensors:view")));
    }
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) Permission(org.keycloak.representations.idm.authorization.Permission) ClientResource(org.keycloak.admin.client.resource.ClientResource) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationResource(org.keycloak.admin.client.resource.AuthorizationResource) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Example 39 with ScopeRepresentation

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

the class PolicyEnforcerTest method testMatchHttpVerbsToScopes.

@Test
public void testMatchHttpVerbsToScopes() {
    ClientResource clientResource = getClientResource(RESOURCE_SERVER_CLIENT_ID);
    ResourceRepresentation resource = createResource(clientResource, "Resource With HTTP Scopes", "/api/resource-with-scope");
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getName());
    permission.addPolicy("Always Grant Policy");
    PermissionsResource permissions = clientResource.authorization().permissions();
    permissions.resource().create(permission).close();
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-match-http-verbs-scopes.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    oauth.realm(REALM_NAME);
    oauth.clientId("public-client-test");
    oauth.doLogin("marta", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    String token = response.getAccessToken();
    OIDCHttpFacade httpFacade = createHttpFacade("/api/resource-with-scope", token);
    AuthorizationContext context = policyEnforcer.enforce(httpFacade);
    assertFalse("Should fail because resource does not have any scope named GET", context.isGranted());
    assertEquals(403, TestResponse.class.cast(httpFacade.getResponse()).getStatus());
    resource.addScope("GET", "POST");
    clientResource.authorization().resources().resource(resource.getId()).update(resource);
    deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-match-http-verbs-scopes.json"));
    policyEnforcer = deployment.getPolicyEnforcer();
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    // create a PATCH scope without associated it with the resource so that a PATCH request is denied accordingly even though
    // the scope exists on the server
    clientResource.authorization().scopes().create(new ScopeRepresentation("PATCH"));
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "PATCH");
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    ScopePermissionRepresentation postPermission = new ScopePermissionRepresentation();
    postPermission.setName("GET permission");
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().create(postPermission).close();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Grant Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    AuthzClient authzClient = getAuthzClient("default-keycloak.json");
    AuthorizationResponse authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("GET");
    postPermission.addPolicy("Always Grant Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    authorize = authzClient.authorization(token).authorize();
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    postPermission = permissions.scope().findByName(postPermission.getName());
    postPermission.addScope("POST");
    postPermission.addPolicy("Always Deny Policy");
    permissions.scope().findById(postPermission.getId()).update(postPermission);
    AuthorizationRequest request = new AuthorizationRequest();
    request.addPermission(null, "GET");
    authorize = authzClient.authorization(token).authorize(request);
    token = authorize.getToken();
    httpFacade = createHttpFacade("/api/resource-with-scope", token);
    context = policyEnforcer.enforce(httpFacade);
    assertTrue(context.isGranted());
    httpFacade = createHttpFacade("/api/resource-with-scope", token, "POST");
    context = policyEnforcer.enforce(httpFacade);
    assertFalse(context.isGranted());
}
Also used : AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) OAuthClient(org.keycloak.testsuite.util.OAuthClient) OIDCHttpFacade(org.keycloak.adapters.OIDCHttpFacade) AuthorizationContext(org.keycloak.AuthorizationContext) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) PermissionsResource(org.keycloak.admin.client.resource.PermissionsResource) AuthzClient(org.keycloak.authorization.client.AuthzClient) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) ClientResource(org.keycloak.admin.client.resource.ClientResource) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ScopePermissionRepresentation(org.keycloak.representations.idm.authorization.ScopePermissionRepresentation) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 40 with ScopeRepresentation

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

the class ResourceManagementWithAuthzClientTest method toResourceRepresentation.

private ResourceRepresentation toResourceRepresentation(AuthzClient authzClient, String id) {
    ResourceRepresentation created = authzClient.protection().resource().findById(id);
    ResourceRepresentation resourceRepresentation = new ResourceRepresentation();
    resourceRepresentation.setId(created.getId());
    resourceRepresentation.setName(created.getName());
    resourceRepresentation.setIconUri(created.getIconUri());
    resourceRepresentation.setUris(created.getUris());
    resourceRepresentation.setType(created.getType());
    resourceRepresentation.setOwner(created.getOwner());
    resourceRepresentation.setScopes(created.getScopes().stream().map(scopeRepresentation -> {
        ScopeRepresentation scope = new ScopeRepresentation();
        scope.setId(scopeRepresentation.getId());
        scope.setName(scopeRepresentation.getName());
        scope.setIconUri(scopeRepresentation.getIconUri());
        return scope;
    }).collect(Collectors.toSet()));
    resourceRepresentation.setAttributes(created.getAttributes());
    return resourceRepresentation;
}
Also used : ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation)

Aggregations

ScopeRepresentation (org.keycloak.representations.idm.authorization.ScopeRepresentation)48 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)27 Test (org.junit.Test)18 ArrayList (java.util.ArrayList)14 List (java.util.List)12 Response (javax.ws.rs.core.Response)11 HashSet (java.util.HashSet)10 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)10 HashMap (java.util.HashMap)8 Map (java.util.Map)8 Set (java.util.Set)8 AuthzClient (org.keycloak.authorization.client.AuthzClient)8 Arrays (java.util.Arrays)7 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)7 PolicyRepresentation (org.keycloak.representations.idm.authorization.PolicyRepresentation)7 Collection (java.util.Collection)6 Collectors (java.util.stream.Collectors)6 ResourceScopesResource (org.keycloak.admin.client.resource.ResourceScopesResource)5 HttpResponseException (org.keycloak.authorization.client.util.HttpResponseException)5 WebElement (org.openqa.selenium.WebElement)5