Beispiel #1
0
  /**
   * Get account information.
   *
   * @return
   */
  @Path("/")
  @GET
  public Response accountPage() {
    List<MediaType> types = headers.getAcceptableMediaTypes();
    if (types.contains(MediaType.WILDCARD_TYPE) || (types.contains(MediaType.TEXT_HTML_TYPE))) {
      return forwardToPage(null, AccountPages.ACCOUNT);
    } else if (types.contains(MediaType.APPLICATION_JSON_TYPE)) {
      requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE);

      UserRepresentation rep = ModelToRepresentation.toRepresentation(auth.getUser());
      if (rep.getAttributes() != null) {
        Iterator<String> itr = rep.getAttributes().keySet().iterator();
        while (itr.hasNext()) {
          if (itr.next().startsWith("keycloak.")) {
            itr.remove();
          }
        }
      }

      return Cors.add(request, Response.ok(rep)).auth().allowedOrigins(auth.getToken()).build();
    } else {
      return Response.notAcceptable(
              Variant.VariantListBuilder.newInstance()
                  .mediaTypes(MediaType.TEXT_HTML_TYPE, MediaType.APPLICATION_JSON_TYPE)
                  .build())
          .build();
    }
  }
  /**
   * Get represenation of the user
   *
   * @param id User id
   * @return
   */
  @Path("{id}")
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public UserRepresentation getUser(final @PathParam("id") String id) {
    auth.requireView();

    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      throw new NotFoundException("User not found");
    }

    UserRepresentation rep = ModelToRepresentation.toRepresentation(user);

    if (realm.isIdentityFederationEnabled()) {
      List<FederatedIdentityRepresentation> reps = getFederatedIdentities(user);
      rep.setFederatedIdentities(reps);
    }

    if (session
        .getProvider(BruteForceProtector.class)
        .isTemporarilyDisabled(session, realm, rep.getUsername())) {
      rep.setEnabled(false);
    }

    return rep;
  }
Beispiel #3
0
  public static UserRepresentation findUserInRealmRep(
      RealmRepresentation testRealm, String username) {
    for (UserRepresentation rep : testRealm.getUsers()) {
      if (rep.getUsername().equals(username)) return rep;
    }

    return null;
  }
  public String createUser() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setEmail("user1@localhost");

    Response response = realm.users().create(user);
    String createdId = ApiUtil.getCreatedId(response);
    response.close();
    return createdId;
  }
  @Test
  public void createDuplicatedUser4() {
    createUser();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("USER1");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    response.close();
  }
  private void createUsers() {
    for (int i = 1; i < 10; i++) {
      UserRepresentation user = new UserRepresentation();
      user.setUsername("username" + i);
      user.setEmail("user" + i + "@localhost");
      user.setFirstName("First" + i);
      user.setLastName("Last" + i);

      realm.users().create(user).close();
    }
  }
  @Test
  public void createDuplicatedUser5() {
    createUser();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user2");
    user.setEmail("User1@localhost");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    response.close();
  }
  @Test
  public void updateUserWithNewUsernameNotPossible() {
    String id = createUser();

    UserResource user = realm.users().get(id);
    UserRepresentation userRep = user.toRepresentation();
    userRep.setUsername("user11");
    user.update(userRep);

    userRep = realm.users().get(id).toRepresentation();
    assertEquals("user1", userRep.getUsername());
  }
  /**
   * Creates a user in the given realm and returns its ID.
   *
   * @param realm Realm name
   * @param username Username
   * @param password Password
   * @param requiredActions
   * @return ID of the newly created user
   */
  public String createUser(
      String realm, String username, String password, String... requiredActions) {
    List<String> requiredUserActions = Arrays.asList(requiredActions);

    UserRepresentation homer = new UserRepresentation();
    homer.setEnabled(true);
    homer.setUsername(username);
    homer.setRequiredActions(requiredUserActions);

    return ApiUtil.createUserAndResetPasswordWithAdminClient(
        adminClient.realm(realm), homer, password);
  }
  @Test
  public void addRequiredAction() {
    String id = createUser();

    UserResource user = realm.users().get(id);
    assertTrue(user.toRepresentation().getRequiredActions().isEmpty());

    UserRepresentation userRep = user.toRepresentation();
    userRep.getRequiredActions().add("UPDATE_PASSWORD");
    user.update(userRep);

    assertEquals(1, user.toRepresentation().getRequiredActions().size());
    assertEquals("UPDATE_PASSWORD", user.toRepresentation().getRequiredActions().get(0));
  }
  @Test
  public void createDuplicatedUser1() {
    createUser();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());

    // Just to show how to retrieve underlying error message
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("User exists with same username", error.getErrorMessage());

    response.close();
  }
  @Before
  public void createUser() {
    log.debug("creating user for realm " + bc.providerRealmName());

    UserRepresentation user = new UserRepresentation();
    user.setUsername(bc.getUserLogin());
    user.setEmail(bc.getUserEmail());
    user.setEmailVerified(true);
    user.setEnabled(true);

    RealmResource realmResource = adminClient.realm(bc.providerRealmName());
    String userId = createUserWithAdminClient(realmResource, user);

    resetUserPassword(realmResource.users().get(userId), bc.getUserPassword(), false);
  }
  public void setRequiredActionEnabled(
      String realm, String userId, String requiredAction, boolean enabled) {
    UsersResource usersResource = adminClient.realm(realm).users();

    UserResource userResource = usersResource.get(userId);
    UserRepresentation userRepresentation = userResource.toRepresentation();

    List<String> requiredActions = userRepresentation.getRequiredActions();
    if (enabled && !requiredActions.contains(requiredAction)) {
      requiredActions.add(requiredAction);
    } else if (!enabled && requiredActions.contains(requiredAction)) {
      requiredActions.remove(requiredAction);
    }

    userResource.update(userRepresentation);
  }
  @Test
  public void updateUserWithNewUsernameAccessingViaOldUsername() {
    switchEditUsernameAllowedOn();
    createUser();

    try {
      UserResource user = realm.users().get("user1");
      UserRepresentation userRep = user.toRepresentation();
      userRep.setUsername("user1");
      user.update(userRep);

      realm.users().get("user11").toRepresentation();
      fail("Expected failure");
    } catch (ClientErrorException e) {
      assertEquals(404, e.getResponse().getStatus());
    }
  }
  @Test
  public void logInAsUserInIDP() {
    driver.navigate().to(getAccountUrl(consumerRealmName()));

    log.debug("Clicking social " + getIDPAlias());
    accountLoginPage.clickSocial(getIDPAlias());

    waitForPage("log in to");

    Assert.assertTrue(
        "Driver should be on the provider realm page right now",
        driver.getCurrentUrl().contains("/auth/realms/" + providerRealmName() + "/"));

    log.debug("Logging in");
    accountLoginPage.login(getUserLogin(), getUserPassword());

    waitForPage("update account information");

    Assert.assertTrue(updateAccountInformationPage.isCurrent());
    Assert.assertTrue(
        "We must be on correct realm right now",
        driver.getCurrentUrl().contains("/auth/realms/" + consumerRealmName() + "/"));

    log.debug("Updating info on updateAccount page");
    updateAccountInformationPage.updateAccountInformation("Firstname", "Lastname");

    UsersResource consumerUsers = adminClient.realm(consumerRealmName()).users();

    int userCount = consumerUsers.count();
    Assert.assertTrue("There must be at least one user", userCount > 0);

    List<UserRepresentation> users = consumerUsers.search("", 0, userCount);

    boolean isUserFound = false;
    for (UserRepresentation user : users) {
      if (user.getUsername().equals(getUserLogin()) && user.getEmail().equals(getUserEmail())) {
        isUserFound = true;
        break;
      }
    }

    Assert.assertTrue(
        "There must be user " + getUserLogin() + " in realm " + consumerRealmName(), isUserFound);

    testSingleLogout();
  }
Beispiel #16
0
  /**
   * Update the user
   *
   * @param id User id
   * @param rep
   * @return
   */
  @Path("{id}")
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updateUser(final @PathParam("id") String id, final UserRepresentation rep) {
    auth.requireManage();

    try {
      UserModel user = session.users().getUserById(id, realm);
      if (user == null) {
        throw new NotFoundException("User not found");
      }

      Set<String> attrsToRemove;
      if (rep.getAttributes() != null) {
        attrsToRemove = new HashSet<>(user.getAttributes().keySet());
        attrsToRemove.removeAll(rep.getAttributes().keySet());
      } else {
        attrsToRemove = Collections.emptySet();
      }

      if (rep.isEnabled() != null && rep.isEnabled()) {
        UsernameLoginFailureModel failureModel =
            session.sessions().getUserLoginFailure(realm, rep.getUsername().toLowerCase());
        if (failureModel != null) {
          failureModel.clearFailures();
        }
      }

      updateUserFromRep(user, rep, attrsToRemove, realm, session);
      adminEvent
          .operation(OperationType.UPDATE)
          .resourcePath(uriInfo)
          .representation(rep)
          .success();

      if (session.getTransaction().isActive()) {
        session.getTransaction().commit();
      }
      return Response.noContent().build();
    } catch (ModelDuplicateException e) {
      return ErrorResponse.exists("User exists with same username or email");
    } catch (ModelReadOnlyException re) {
      return ErrorResponse.exists("User is read only!");
    }
  }
  @Test
  public void sendVerifyEmail() {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setUsername("user1");
    Response response = realm.users().create(userRep);
    String id = ApiUtil.getCreatedId(response);
    response.close();

    UserResource user = realm.users().get(id);

    try {
      user.sendVerifyEmail();
      fail("Expected failure");
    } catch (ClientErrorException e) {
      assertEquals(400, e.getResponse().getStatus());

      ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
      Assert.assertEquals("User email missing", error.getErrorMessage());
    }
    try {
      userRep = user.toRepresentation();
      userRep.setEmail("user1@localhost");
      userRep.setEnabled(false);
      user.update(userRep);
      user.sendVerifyEmail();
      fail("Expected failure");
    } catch (ClientErrorException e) {
      assertEquals(400, e.getResponse().getStatus());

      ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
      Assert.assertEquals("User is disabled", error.getErrorMessage());
    }
    try {
      userRep.setEnabled(true);
      user.update(userRep);
      user.sendVerifyEmail("invalidClientId");
      fail("Expected failure");
    } catch (ClientErrorException e) {
      assertEquals(400, e.getResponse().getStatus());

      ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
      Assert.assertEquals("invalidClientId not enabled", error.getErrorMessage());
    }
  }
  @Test
  public void updateUserWithExistingUsername() {
    switchEditUsernameAllowedOn();
    createUser();

    UserRepresentation userRep = new UserRepresentation();
    userRep.setUsername("user2");
    Response response = realm.users().create(userRep);
    String createdId = ApiUtil.getCreatedId(response);
    response.close();

    try {
      UserResource user = realm.users().get(createdId);
      userRep = user.toRepresentation();
      userRep.setUsername("user1");
      user.update(userRep);
      fail("Expected failure");
    } catch (ClientErrorException e) {
      assertEquals(409, e.getResponse().getStatus());
    }
  }
Beispiel #19
0
  /**
   * Create a new user
   *
   * <p>Username must be unique.
   *
   * @param uriInfo
   * @param rep
   * @return
   */
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createUser(final @Context UriInfo uriInfo, final UserRepresentation rep) {
    auth.requireManage();

    // Double-check duplicated username and email here due to federation
    if (session.users().getUserByUsername(rep.getUsername(), realm) != null) {
      return ErrorResponse.exists("User exists with same username");
    }
    if (rep.getEmail() != null && session.users().getUserByEmail(rep.getEmail(), realm) != null) {
      return ErrorResponse.exists("User exists with same email");
    }

    try {
      UserModel user = session.users().addUser(realm, rep.getUsername());
      Set<String> emptySet = Collections.emptySet();
      updateUserFromRep(user, rep, emptySet, realm, session);

      adminEvent
          .operation(OperationType.CREATE)
          .resourcePath(uriInfo, user.getId())
          .representation(rep)
          .success();

      if (session.getTransaction().isActive()) {
        session.getTransaction().commit();
      }

      return Response.created(uriInfo.getAbsolutePathBuilder().path(user.getId()).build()).build();
    } catch (ModelDuplicateException e) {
      if (session.getTransaction().isActive()) {
        session.getTransaction().setRollbackOnly();
      }
      return ErrorResponse.exists("User exists with same username or email");
    }
  }
Beispiel #20
0
  @Test
  public void addUserTest() throws Throwable {
    AddUser.main(new String[] {"-u", "addusertest-admin", "-p", "password"});
    assertEquals(1, dir.listFiles().length);

    List<RealmRepresentation> realms =
        JsonSerialization.readValue(
            new FileInputStream(new File(dir, "keycloak-add-user.json")),
            new TypeReference<List<RealmRepresentation>>() {});
    assertEquals(1, realms.size());
    assertEquals(1, realms.get(0).getUsers().size());

    UserRepresentation user = realms.get(0).getUsers().get(0);
    assertEquals(new Integer(100000), user.getCredentials().get(0).getHashIterations());
    assertNull(user.getCredentials().get(0).getValue());

    CredentialRepresentation credentials = user.getCredentials().get(0);

    assertEquals(Pbkdf2PasswordHashProvider.ID, credentials.getAlgorithm());
    assertEquals(new Integer(100000), credentials.getHashIterations());

    KeycloakServer server = new KeycloakServer();
    try {
      server.start();

      Keycloak keycloak =
          Keycloak.getInstance(
              "http://localhost:8081/auth",
              "master",
              "addusertest-admin",
              "password",
              Constants.ADMIN_CLI_CLIENT_ID);
      keycloak.realms().findAll();

      RealmRepresentation testRealm = new RealmRepresentation();
      testRealm.setEnabled(true);
      testRealm.setId("test");
      testRealm.setRealm("test");

      keycloak.realms().create(testRealm);

      RealmResource realm = keycloak.realm("master");

      List<UserRepresentation> users =
          realm.users().search("addusertest-admin", null, null, null, null, null);
      assertEquals(1, users.size());

      UserRepresentation created = users.get(0);
      assertNotNull(created.getCreatedTimestamp());

      UserResource userResource = realm.users().get(created.getId());

      List<RoleRepresentation> realmRoles = userResource.roles().realmLevel().listAll();

      assertRoles(realmRoles, "admin", "offline_access");

      List<ClientRepresentation> clients = realm.clients().findAll();
      String accountId = null;
      for (ClientRepresentation c : clients) {
        if (c.getClientId().equals("account")) {
          accountId = c.getId();
        }
      }

      List<RoleRepresentation> accountRoles = userResource.roles().clientLevel(accountId).listAll();

      assertRoles(accountRoles, "view-profile", "manage-account");

      keycloak.close();

      assertEquals(0, dir.listFiles().length);
    } finally {
      server.stop();
    }
  }
  @Test
  public void attributes() {
    UserRepresentation user1 = new UserRepresentation();
    user1.setUsername("user1");
    user1.singleAttribute("attr1", "value1user1");
    user1.singleAttribute("attr2", "value2user1");

    Response response = realm.users().create(user1);
    String user1Id = ApiUtil.getCreatedId(response);
    response.close();

    UserRepresentation user2 = new UserRepresentation();
    user2.setUsername("user2");
    user2.singleAttribute("attr1", "value1user2");
    List<String> vals = new ArrayList<>();
    vals.add("value2user2");
    vals.add("value2user2_2");
    user2.getAttributesAsListValues().put("attr2", vals);

    response = realm.users().create(user2);
    String user2Id = ApiUtil.getCreatedId(response);
    response.close();
    user1 = realm.users().get(user1Id).toRepresentation();
    assertEquals(2, user1.getAttributesAsListValues().size());
    assertAttributeValue("value1user1", user1.getAttributesAsListValues().get("attr1"));
    assertAttributeValue("value2user1", user1.getAttributesAsListValues().get("attr2"));

    user2 = realm.users().get(user2Id).toRepresentation();
    assertEquals(2, user2.getAttributesAsListValues().size());
    assertAttributeValue("value1user2", user2.getAttributesAsListValues().get("attr1"));
    vals = user2.getAttributesAsListValues().get("attr2");
    assertEquals(2, vals.size());
    assertTrue(vals.contains("value2user2") && vals.contains("value2user2_2"));

    user1.singleAttribute("attr1", "value3user1");
    user1.singleAttribute("attr3", "value4user1");

    realm.users().get(user1Id).update(user1);

    user1 = realm.users().get(user1Id).toRepresentation();
    assertEquals(3, user1.getAttributesAsListValues().size());
    assertAttributeValue("value3user1", user1.getAttributesAsListValues().get("attr1"));
    assertAttributeValue("value2user1", user1.getAttributesAsListValues().get("attr2"));
    assertAttributeValue("value4user1", user1.getAttributesAsListValues().get("attr3"));

    user1.getAttributes().remove("attr1");
    realm.users().get(user1Id).update(user1);

    user1 = realm.users().get(user1Id).toRepresentation();
    assertEquals(2, user1.getAttributesAsListValues().size());
    assertAttributeValue("value2user1", user1.getAttributesAsListValues().get("attr2"));
    assertAttributeValue("value4user1", user1.getAttributesAsListValues().get("attr3"));

    user1.getAttributes().clear();
    realm.users().get(user1Id).update(user1);

    user1 = realm.users().get(user1Id).toRepresentation();
    assertNull(user1.getAttributes());
  }
Beispiel #22
0
  public static void updateUserFromRep(
      UserModel user,
      UserRepresentation rep,
      Set<String> attrsToRemove,
      RealmModel realm,
      KeycloakSession session) {
    if (realm.isEditUsernameAllowed()) {
      user.setUsername(rep.getUsername());
    }
    user.setEmail(rep.getEmail());
    user.setFirstName(rep.getFirstName());
    user.setLastName(rep.getLastName());

    if (rep.isEnabled() != null) user.setEnabled(rep.isEnabled());
    if (rep.isTotp() != null) user.setOtpEnabled(rep.isTotp());
    if (rep.isEmailVerified() != null) user.setEmailVerified(rep.isEmailVerified());

    List<String> reqActions = rep.getRequiredActions();

    if (reqActions != null) {
      Set<String> allActions = new HashSet<>();
      for (ProviderFactory factory :
          session.getKeycloakSessionFactory().getProviderFactories(RequiredActionProvider.class)) {
        allActions.add(factory.getId());
      }
      for (String action : allActions) {
        if (reqActions.contains(action)) {
          user.addRequiredAction(action);
        } else {
          user.removeRequiredAction(action);
        }
      }
    }

    if (rep.getAttributesAsListValues() != null) {
      for (Map.Entry<String, List<String>> attr : rep.getAttributesAsListValues().entrySet()) {
        user.setAttribute(attr.getKey(), attr.getValue());
      }

      for (String attr : attrsToRemove) {
        user.removeAttribute(attr);
      }
    }
  }
 private UserRepresentation createAdminUserRepresentation() {
   UserRepresentation adminUserRep = new UserRepresentation();
   adminUserRep.setUsername(ADMIN);
   setPasswordFor(adminUserRep, ADMIN);
   return adminUserRep;
 }
Beispiel #24
0
 public void setValues(UserRepresentation user) {
   setUsername(user.getUsername());
   setEmail(user.getEmail());
   setFirstName(user.getFirstName());
   setLastName(user.getLastName());
 }
  @Override
  public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation rep = new RealmRepresentation();
    rep.setEnabled(true);
    rep.setRealm(REALM_NAME);
    rep.setUsers(new LinkedList<UserRepresentation>());

    LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation password = new CredentialRepresentation();
    password.setType(CredentialRepresentation.PASSWORD);
    password.setValue("password");
    credentials.add(password);

    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setUsername("manage-clients");
    user.setCredentials(credentials);
    user.setClientRoles(
        Collections.singletonMap(
            Constants.REALM_MANAGEMENT_CLIENT_ID,
            Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));

    rep.getUsers().add(user);

    UserRepresentation user2 = new UserRepresentation();
    user2.setEnabled(true);
    user2.setUsername("create-clients");
    user2.setCredentials(credentials);
    user2.setClientRoles(
        Collections.singletonMap(
            Constants.REALM_MANAGEMENT_CLIENT_ID,
            Collections.singletonList(AdminRoles.CREATE_CLIENT)));

    rep.getUsers().add(user2);

    UserRepresentation user3 = new UserRepresentation();
    user3.setEnabled(true);
    user3.setUsername("no-access");
    user3.setCredentials(credentials);

    rep.getUsers().add(user3);

    testRealms.add(rep);
  }