org.keycloak.events.admin.OperationType Java Examples

The following examples show how to use org.keycloak.events.admin.OperationType. 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: ClientResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Register a cluster node with the client
 *
 * Manually register cluster node to this client - usually it's not needed to call this directly as adapter should handle
 * by sending registration request to Keycloak
 *
 * @param formParams
 */
@Path("nodes")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void registerNode(Map<String, String> formParams) {
    auth.clients().requireConfigure(client);

    String node = formParams.get("node");
    if (node == null) {
        throw new BadRequestException("Node not found in params");
    }
    
    ReservedCharValidator.validate(node);
    
    if (logger.isDebugEnabled()) logger.debug("Register node: " + node);
    client.registerNode(node, Time.currentTime());
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.CLUSTER_NODE).resourcePath(session.getContext().getUri(), node).success();
}
 
Example #2
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Upload only certificate, not private key
 *
 * @param input
 * @return information extracted from uploaded certificate - not necessarily the new state of certificate on the server
 * @throws IOException
 */
@POST
@Path("upload-certificate")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation uploadJksCertificate(MultipartFormDataInput input) throws IOException {
    auth.clients().requireConfigure(client);

    try {
        CertificateRepresentation info = getCertFromRequest(input);
        info.setPrivateKey(null);
        CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

        adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();
        return info;
    } catch (IllegalStateException ise) {
        throw new ErrorResponseException("certificate-not-found", "Certificate or key with given alias not found in the keystore", Response.Status.BAD_REQUEST);
    }
}
 
Example #3
Source File: AbstractX509AuthenticationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
AuthenticationFlowRepresentation createFlow(AuthenticationFlowRepresentation flowRep) {
    Response response = authMgmtResource.createFlow(flowRep);
    try {
        org.keycloak.testsuite.Assert.assertEquals(201, response.getStatus());
    }
    finally {
        response.close();
    }
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AssertAdminEvents.isExpectedPrefixFollowedByUuid(AdminEventPaths.authFlowsPath()), flowRep, ResourceType.AUTH_FLOW);

    for (AuthenticationFlowRepresentation flow : authMgmtResource.getFlows()) {
        if (flow.getAlias().equalsIgnoreCase(flowRep.getAlias())) {
            return flow;
        }
    }
    return null;
}
 
Example #4
Source File: ClientTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private ClientRepresentation createClient() {
    ClientRepresentation rep = new ClientRepresentation();
    rep.setClientId("my-app");
    rep.setDescription("my-app description");
    rep.setEnabled(true);
    Response response = realm.clients().create(rep);
    response.close();
    String id = ApiUtil.getCreatedId(response);
    getCleanup().addClientUuid(id);
    ClientRepresentation found = ApiUtil.findClientResourceByClientId(realm, "my-app").toRepresentation();

    assertEquals("my-app", found.getClientId());
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(id), rep, ResourceType.CLIENT);

    rep.setId(id);

    return rep;
}
 
Example #5
Source File: AuthenticatorConfigTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateConfig() {
    AuthenticatorConfigRepresentation cfg = newConfig("foo", IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION, "true");

    // Attempt to create config for non-existent execution
    Response response = authMgmtResource.newExecutionConfig("exec-id-doesnt-exists", cfg);
    Assert.assertEquals(404, response.getStatus());
    response.close();

    // Create config success
    String cfgId = createConfig(executionId, cfg);

    // Assert found
    AuthenticatorConfigRepresentation cfgRep = authMgmtResource.getAuthenticatorConfig(cfgId);
    assertConfig(cfgRep, cfgId, "foo", IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION, "true");

    // Cleanup
    authMgmtResource.removeAuthenticatorConfig(cfgId);
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.DELETE, AdminEventPaths.authExecutionConfigPath(cfgId), ResourceType.AUTHENTICATOR_CONFIG);
}
 
Example #6
Source File: ResourceSetService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("{id}")
@DELETE
public Response delete(@PathParam("id") String id) {
    requireManage();
    StoreFactory storeFactory = authorization.getStoreFactory();
    Resource resource = storeFactory.getResourceStore().findById(id, resourceServer.getId());

    if (resource == null) {
        return Response.status(Status.NOT_FOUND).build();
    }

    storeFactory.getResourceStore().delete(id);

    audit(toRepresentation(resource, resourceServer, authorization), OperationType.DELETE);

    return Response.noContent().build();
}
 
Example #7
Source File: FlowTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
// KEYCLOAK-2580
public void addExecutionFlow() {
    HashMap<String, String> params = new HashMap<>();
    params.put("newName", "parent");
    Response response = authMgmtResource.copy("browser", params);
    Assert.assertEquals(201, response.getStatus());
    response.close();
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authCopyFlowPath("browser"), params, ResourceType.AUTH_FLOW);

    params = new HashMap<>();
    params.put("alias", "child");
    params.put("description", "Description");
    params.put("provider", "registration-page-form");
    params.put("type", "basic-flow");

    authMgmtResource.addExecutionFlow("parent", params);
    assertAdminEvents.assertEvent(REALM_NAME, OperationType.CREATE, AdminEventPaths.authAddExecutionFlowPath("parent"), params, ResourceType.AUTH_EXECUTION_FLOW);
}
 
Example #8
Source File: PolicyResourceService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@PUT
@Consumes("application/json")
@Produces("application/json")
@NoCache
public Response update(String payload) {
    if (auth != null) {
        this.auth.realm().requireManageAuthorization();
    }

    AbstractPolicyRepresentation representation = doCreateRepresentation(payload);

    if (policy == null) {
        return Response.status(Status.NOT_FOUND).build();
    }

    representation.setId(policy.getId());

    RepresentationToModel.toModel(representation, authorization, policy);


    audit(representation, OperationType.UPDATE);

    return Response.status(Status.CREATED).build();
}
 
Example #9
Source File: UserResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Revoke consent and offline tokens for particular client from user
 *
 * @param clientId Client id
 */
@Path("consents/{client}")
@DELETE
@NoCache
public void revokeConsent(final @PathParam("client") String clientId) {
    auth.users().requireManage(user);

    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null) {
        throw new NotFoundException("Client not found");
    }
    boolean revokedConsent = session.users().revokeConsentForClient(realm, user.getId(), client.getId());
    boolean revokedOfflineToken = new UserSessionManager(session).revokeOfflineToken(user, client);

    if (revokedConsent) {
        // Logout clientSessions for this user and client
        AuthenticationManager.backchannelLogoutUserFromClient(session, realm, user, client, session.getContext().getUri(), headers);
    }

    if (!revokedConsent && !revokedOfflineToken) {
        throw new NotFoundException("Consent nor offline token not found");
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
 
Example #10
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test06UpdateSamlMapper() {
    ProtocolMapperRepresentation rep = makeSamlMapper("saml-role-name-mapper2");

    Response resp = samlMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    rep.getConfig().put("role", "account.manage-account");
    rep.setId(createdId);
    samlMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientScopeProtocolMapperPath(samlClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    ProtocolMapperRepresentation updated = samlMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}
 
Example #11
Source File: ClientScopeProtocolMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void test07UpdateOidcMapper() {
    ProtocolMapperRepresentation rep = makeOidcMapper("oidc-hardcoded-role-mapper2");

    Response resp = oidcMappersRsc.createMapper(rep);
    resp.close();
    String createdId = ApiUtil.getCreatedId(resp);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientScopeProtocolMapperPath(oidcClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    rep.getConfig().put("role", "myotherrole");
    rep.setId(createdId);
    oidcMappersRsc.update(createdId, rep);
    assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientScopeProtocolMapperPath(oidcClientScopeId, createdId), rep, ResourceType.PROTOCOL_MAPPER);

    ProtocolMapperRepresentation updated = oidcMappersRsc.getMapperById(createdId);
    assertEqualMappers(rep, updated);
}
 
Example #12
Source File: ClientResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Unregister a cluster node from the client
 *
 * @param node
 */
@Path("nodes/{node}")
@DELETE
@NoCache
public void unregisterNode(final @PathParam("node") String node) {
    auth.clients().requireConfigure(client);

    if (logger.isDebugEnabled()) logger.debug("Unregister node: " + node);

    Integer time = client.getRegisteredNodes().get(node);
    if (time == null) {
        throw new NotFoundException("Client does not have node ");
    }
    client.unregisterNode(node);
    adminEvent.operation(OperationType.DELETE).resource(ResourceType.CLUSTER_NODE).resourcePath(session.getContext().getUri()).success();
}
 
Example #13
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void groupMembershipPaginated() {
    String userId = createUser(UserBuilder.create().username("user-a").build());

    for (int i = 1; i <= 10; i++) {
        GroupRepresentation group = new GroupRepresentation();
        group.setName("group-" + i);
        String groupId = createGroup(realm, group).getId();
        realm.users().get(userId).joinGroup(groupId);
        assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
    }

    List<GroupRepresentation> groups = realm.users().get(userId).groups(5, 6);
    assertEquals(groups.size(), 5);
    assertNames(groups, "group-5","group-6","group-7","group-8","group-9");
}
 
Example #14
Source File: IdentityProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemove() {
    IdentityProviderRepresentation newIdentityProvider = createRep("remove-identity-provider", "saml");

    create(newIdentityProvider);

    IdentityProviderResource identityProviderResource = realm.identityProviders().get("remove-identity-provider");

    assertNotNull(identityProviderResource);

    IdentityProviderRepresentation representation = identityProviderResource.toRepresentation();

    assertNotNull(representation);

    identityProviderResource.remove();
    assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.identityProviderPath("remove-identity-provider"), ResourceType.IDENTITY_PROVIDER);

    try {
        realm.identityProviders().get("remove-identity-provider").toRepresentation();
        Assert.fail("Not expected to found");
    } catch (NotFoundException nfe) {
        // Expected
    }
}
 
Example #15
Source File: RoleResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void deleteComposites(AdminEventBuilder adminEvent, UriInfo uriInfo, List<RoleRepresentation> roles, RoleModel role) {
    for (RoleRepresentation rep : roles) {
        RoleModel composite = realm.getRoleById(rep.getId());
        if (composite == null) {
            throw new NotFoundException("Could not find composite role");
        }
        role.removeCompositeRole(composite);
    }

    if (role.isClientRole()) {
        adminEvent.resource(ResourceType.CLIENT_ROLE);
    } else {
        adminEvent.resource(ResourceType.REALM_ROLE);
    }

    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).representation(roles).success();
}
 
Example #16
Source File: ClientRoleMappingsResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Add client-level roles to the user role mapping
 *
 * @param roles
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addClientRoleMapping(List<RoleRepresentation> roles) {
    managePermission.require();

    try {
        for (RoleRepresentation role : roles) {
            RoleModel roleModel = client.getRole(role.getName());
            if (roleModel == null || !roleModel.getId().equals(role.getId())) {
                throw new NotFoundException("Role not found");
            }
            auth.roles().requireMapRole(roleModel);
            user.grantRole(roleModel);
        }
    } catch (ModelException | ReadOnlyException me) {
        logger.warn(me.getMessage(), me);
        throw new ErrorResponseException("invalid_request", "Could not add user role mappings!", Response.Status.BAD_REQUEST);
    }

    adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(roles).success();

}
 
Example #17
Source File: ClientRolesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void getRolesWithBriefRepresentation() {
    for(int i = 0; i<5; i++) {
        String roleName = "attributesrole"+i;
        RoleRepresentation role = makeRole(roleName);
        
        Map<String, List<String>> attributes = new HashMap<String, List<String>>();
        attributes.put("attribute1", Arrays.asList("value1","value2"));
        role.setAttributes(attributes);
                
        rolesRsc.create(role);
        assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientDbId,roleName), role, ResourceType.CLIENT_ROLE);  
        
        // we have to update the role to set the attributes because
        // the add role endpoint only care about name and description
        RoleResource roleToUpdate = rolesRsc.get(roleName);
        role.setId(roleToUpdate.toRepresentation().getId());
        
        roleToUpdate.update(role);
        assertAdminEvents.assertEvent(getRealmId(), OperationType.UPDATE, AdminEventPaths.clientRoleResourcePath(clientDbId,roleName), role, ResourceType.CLIENT_ROLE);         
    }
    
    List<RoleRepresentation> roles = rolesRsc.list();
    assertNull(roles.get(0).getAttributes());
}
 
Example #18
Source File: ClientRolesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testPaginationRoles() {
    
    for(int i = 0; i<15; i++) {
        String roleName = "role"+i;
        RoleRepresentation role = makeRole(roleName);
        rolesRsc.create(role);
        assertAdminEvents.assertEvent(getRealmId(), OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientDbId,roleName), role, ResourceType.CLIENT_ROLE);           
    }  
    
    List<RoleRepresentation> resultSearchWithoutPagination = rolesRsc.list();
    assertEquals(15,resultSearchWithoutPagination.size());
    
    List<RoleRepresentation> resultSearchPagination = rolesRsc.list(1, 5);
    assertEquals(5,resultSearchPagination.size());
    
    List<RoleRepresentation> resultSearchPaginationIncoherentParams = rolesRsc.list(1, null);
    assertTrue(resultSearchPaginationIncoherentParams.size() >= 15);
}
 
Example #19
Source File: InstallationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testOidcBearerOnlyJsonWithAudienceClientScope() {
    // Generate audience client scope
    String clientScopeId = testingClient.testing().generateAudienceClientScope("test", OIDC_NAME_BEARER_ONLY_NAME);

    String json = oidcBearerOnlyClient.getInstallationProvider("keycloak-oidc-keycloak-json");
    assertOidcInstallationConfig(json);
    assertThat(json, containsString("bearer-only"));
    assertThat(json, not(containsString("public-client")));
    assertThat(json, not(containsString("credentials")));
    assertThat(json, containsString("verify-token-audience"));

    // Remove clientScope
    testRealmResource().clientScopes().get(clientScopeId).remove();
    assertAdminEvents.assertEvent(getRealmId(), OperationType.DELETE, AdminEventPaths.clientScopeResourcePath(clientScopeId), null, ResourceType.CLIENT_SCOPE);
}
 
Example #20
Source File: JpaEventStoreProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static AdminEvent convertAdminEvent(AdminEventEntity adminEventEntity) {
    AdminEvent adminEvent = new AdminEvent();
    adminEvent.setTime(adminEventEntity.getTime());
    adminEvent.setRealmId(adminEventEntity.getRealmId());
    setAuthDetails(adminEvent, adminEventEntity);
    adminEvent.setOperationType(OperationType.valueOf(adminEventEntity.getOperationType()));

    if (adminEventEntity.getResourceType() != null) {
        adminEvent.setResourceTypeAsString(adminEventEntity.getResourceType());
    }

    adminEvent.setResourcePath(adminEventEntity.getResourcePath());
    adminEvent.setError(adminEventEntity.getError());
    
    if(adminEventEntity.getRepresentation() != null) {
        adminEvent.setRepresentation(adminEventEntity.getRepresentation());
    }
    return adminEvent;
}
 
Example #21
Source File: AttackDetectionResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Clear any user login failures for the user
 *
 * This can release temporary disabled user
 *
 * @param userId
 */
@Path("brute-force/users/{userId}")
@DELETE
public void clearBruteForceForUser(@PathParam("userId") String userId) {
    UserModel user = session.users().getUserById(userId, realm);
    if (user == null) {
        auth.users().requireManage();
    } else {
        auth.users().requireManage(user);
    }
    UserLoginFailureModel model = session.sessions().getUserLoginFailure(realm, userId);
    if (model != null) {
        session.sessions().removeUserLoginFailure(realm, userId);
        adminEvent.operation(OperationType.DELETE).resourcePath(session.getContext().getUri()).success();
    }
}
 
Example #22
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createUserWithFederationLink() {

    // add a dummy federation provider
    ComponentRepresentation dummyFederationProvider = new ComponentRepresentation();
    dummyFederationProvider.setId(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setName(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setProviderType(UserStorageProvider.class.getName());
    adminClient.realms().realm(REALM_NAME).components().add(dummyFederationProvider);

    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.componentPath(DummyUserFederationProviderFactory.PROVIDER_NAME), dummyFederationProvider, ResourceType.COMPONENT);

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setEmail("user1@localhost");
    user.setFederationLink(DummyUserFederationProviderFactory.PROVIDER_NAME);

    String userId = createUser(user);

    // fetch user again and see federation link filled in
    UserRepresentation createdUser = realm.users().get(userId).toRepresentation();
    assertNotNull(createdUser);
    assertEquals(user.getFederationLink(), createdUser.getFederationLink());
}
 
Example #23
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Delete authenticator configuration
 * @param id Configuration id
 */
@Path("config/{id}")
@DELETE
@NoCache
public void removeAuthenticatorConfig(@PathParam("id") String id) {
    auth.realm().requireManageRealm();

    AuthenticatorConfigModel config = realm.getAuthenticatorConfigById(id);
    if (config == null) {
        throw new NotFoundException("Could not find authenticator config");

    }
    for (AuthenticationFlowModel flow : realm.getAuthenticationFlows()) {
        for (AuthenticationExecutionModel exe : realm.getAuthenticationExecutions(flow.getId())) {
            if (id.equals(exe.getAuthenticatorConfig())) {
                exe.setAuthenticatorConfig(null);
                realm.updateAuthenticatorExecution(exe);
            }
        }
    }

    realm.removeAuthenticatorConfig(config);

    adminEvent.operation(OperationType.DELETE).resource(ResourceType.AUTHENTICATOR_CONFIG).resourcePath(session.getContext().getUri()).success();
}
 
Example #24
Source File: RealmTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void logoutAll() {
    setupTestAppAndUser();

    Response response = realm.users().create(UserBuilder.create().username("user").build());
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), ResourceType.USER);

    realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build());
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResetPasswordPath(userId), ResourceType.USER);

    oauth.doLogin("user", "password");

    GlobalRequestResult globalRequestResult = realm.logoutAll();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, "logout-all", globalRequestResult, ResourceType.REALM);

    assertEquals(1, globalRequestResult.getSuccessRequests().size());
    assertEquals(oauth.AUTH_SERVER_ROOT + "/realms/master/app/admin", globalRequestResult.getSuccessRequests().get(0));
    assertNull(globalRequestResult.getFailedRequests());

    assertNotNull(testingClient.testApp().getAdminLogoutAction());
}
 
Example #25
Source File: RealmRolesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void getRolesWithBriefRepresentation() {
    for(int i = 0; i<5; i++) {
        String roleName = "attributesrolebrief"+i;
        RoleRepresentation role = makeRole(roleName);
        
        Map<String, List<String>> attributes = new HashMap<String, List<String>>();
        attributes.put("attribute1", Arrays.asList("value1","value2"));
        role.setAttributes(attributes);
                
        resource.create(role);
        assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.roleResourcePath(roleName), role, ResourceType.REALM_ROLE);
        
        // we have to update the role to set the attributes because
        // the add role endpoint only care about name and description
        RoleResource roleToUpdate = resource.get(roleName);
        role.setId(roleToUpdate.toRepresentation().getId());
        
        roleToUpdate.update(role);
        assertAdminEvents.assertEvent(realmId, OperationType.UPDATE, AdminEventPaths.roleResourcePath(roleName), role, ResourceType.REALM_ROLE);  
    }
    
    List<RoleRepresentation> roles = resource.list("attributesrolebrief", true);
    assertNull(roles.get(0).getAttributes());
}
 
Example #26
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void groupMembershipSearch() {
    String userId = createUser(UserBuilder.create().username("user-b").build());

    for (int i = 1; i <= 10; i++) {
        GroupRepresentation group = new GroupRepresentation();
        group.setName("group-" + i);
        String groupId = createGroup(realm, group).getId();
        realm.users().get(userId).joinGroup(groupId);
        assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
    }

    List<GroupRepresentation> groups = realm.users().get(userId).groups("-3", 0, 10);
    assertEquals(1, groups.size());
    assertNames(groups, "group-3");

    List<GroupRepresentation> groups2 = realm.users().get(userId).groups("1", 0, 10);
    assertEquals(2, groups2.size());
    assertNames(groups2, "group-1", "group-10");

    List<GroupRepresentation> groups3 = realm.users().get(userId).groups("1", 2, 10);
    assertEquals(0, groups3.size());

    List<GroupRepresentation> groups4 = realm.users().get(userId).groups("gr", 2, 10);
    assertEquals(8, groups4.size());

    List<GroupRepresentation> groups5 = realm.users().get(userId).groups("Gr", 2, 10);
    assertEquals(8, groups5.size());
}
 
Example #27
Source File: ClientResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Update the client
 * @param rep
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response update(final ClientRepresentation rep) {
    auth.clients().requireConfigure(client);

    ValidationMessages validationMessages = new ValidationMessages();
    if (!ClientValidator.validate(rep, validationMessages) || !PairwiseClientValidator.validate(session, rep, validationMessages)) {
        Properties messages = AdminRoot.getMessages(session, realm, auth.adminAuth().getToken().getLocale());
        throw new ErrorResponseException(
                validationMessages.getStringMessages(),
                validationMessages.getStringMessages(messages),
                Response.Status.BAD_REQUEST
        );
    }

    try {
        updateClientFromRep(rep, client, session);

        ClientValidationUtil.validate(session, client, false, c -> {
            session.getTransactionManager().setRollbackOnly();
            throw new ErrorResponseException(Errors.INVALID_INPUT ,c.getError(), Response.Status.BAD_REQUEST);
        });

        adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
        return Response.noContent().build();
    } catch (ModelDuplicateException e) {
        return ErrorResponse.exists("Client already exists");
    }
}
 
Example #28
Source File: RealmAdminResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a specific user session. Any client that has an admin url will also be told to invalidate this
 * particular session.
 *
 * @param sessionId
 */
@Path("sessions/{session}")
@DELETE
public void deleteSession(@PathParam("session") String sessionId) {
    auth.users().requireManage();

    UserSessionModel userSession = session.sessions().getUserSession(realm, sessionId);
    if (userSession == null) throw new NotFoundException("Sesssion not found");
    AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), connection, headers, true);
    adminEvent.operation(OperationType.DELETE).resource(ResourceType.USER_SESSION).resourcePath(session.getContext().getUri()).success();

}
 
Example #29
Source File: ClientTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void removeClient() {
    String id = createClient().getId();

    assertNotNull(ApiUtil.findClientByClientId(realm, "my-app"));
    realm.clients().get(id).remove();
    assertNull(ApiUtil.findClientResourceByClientId(realm, "my-app"));
    assertAdminEvents.assertEvent(realmId, OperationType.DELETE, AdminEventPaths.clientResourcePath(id), ResourceType.CLIENT);
}
 
Example #30
Source File: RealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setupTestAppAndUser() {
    testingClient.testApp().clearAdminActions();

    String redirectUri = oauth.getRedirectUri().replace("/master/", "/" + REALM_NAME + "/");

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("test-app");
    client.setAdminUrl(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/app/admin");
    client.setRedirectUris(Collections.singletonList(redirectUri));
    client.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    client.setSecret("secret");
    Response resp = realm.clients().create(client);
    String clientDbId = ApiUtil.getCreatedId(resp);
    getCleanup().addClientUuid(clientDbId);
    resp.close();
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(clientDbId), client, ResourceType.CLIENT);

    oauth.realm(REALM_NAME);
    oauth.redirectUri(redirectUri);

    UserRepresentation userRep = UserBuilder.create().username("testuser").build();
    Response response = realm.users().create(userRep);
    String userId = ApiUtil.getCreatedId(response);
    response.close();
    getCleanup().addUserId(userId);
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userResourcePath(userId), userRep, ResourceType.USER);

    realm.users().get(userId).resetPassword(CredentialBuilder.create().password("password").build());
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResetPasswordPath(userId), ResourceType.USER);

    testingClient.testApp().clearAdminActions();
}