public static void uploadSP() {
    try {
      Keycloak keycloak =
          Keycloak.getInstance(
              "http://localhost:8081/auth",
              "master",
              "admin",
              "admin",
              Constants.ADMIN_CLI_CLIENT_ID,
              null);
      RealmResource admin = keycloak.realm("demo");

      admin.toRepresentation();

      ClientRepresentation clientRep =
          admin.convertClientDescription(
              IOUtils.toString(
                  SamlPicketlinkSPTest.class.getResourceAsStream("/saml/sp-metadata.xml")));
      Response response = admin.clients().create(clientRep);

      assertEquals(201, response.getStatus());

      keycloak.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
 public void importRealm(RealmRepresentation realm) {
   log.debug("importing realm: " + realm.getRealm());
   try { // TODO - figure out a way how to do this without try-catch
     RealmResource realmResource = adminClient.realms().realm(realm.getRealm());
     RealmRepresentation rRep = realmResource.toRepresentation();
     log.debug("realm already exists on server, re-importing");
     realmResource.remove();
   } catch (NotFoundException nfe) {
     // expected when realm does not exist
   }
   adminClient.realms().create(realm);
 }
 public void removeRealm(String realmName) {
   log.info("removing realm: " + realmName);
   try {
     adminClient.realms().realm(realmName).remove();
   } catch (NotFoundException e) {
   }
 }
  @After
  public void afterAbstractKeycloakTest() {
    if (resetTimeOffset) {
      resetTimeOffset();
    }

    removeTestRealms(); // Remove realms after tests. Tests should cleanup after themselves!
    adminClient.close(); // don't keep admin connection open
  }
  @Test
  public void testBootWithBadProviderId() throws Exception {
    KeycloakSession session = keycloakRule.startSession();
    // set this system property
    System.setProperty(RealmAdapter.COMPONENT_PROVIDER_EXISTS_DISABLED, "true");
    RealmModel realm = session.realms().getRealmByName("master");
    String masterId = realm.getId();
    UserStorageProviderModel model;
    model = new UserStorageProviderModel();
    model.setName("bad-provider-id");
    model.setPriority(2);
    model.setParentId(realm.getId());
    model.setProviderId("error");
    ComponentModel component = realm.importComponentModel(model);

    keycloakRule.stopSession(session, true);

    keycloakRule.restartServer();
    keycloakRule.deployServlet("app", "/app", ApplicationServlet.class);

    loginSuccessAndLogout("test-user@localhost", "password");

    // make sure we can list components and delete provider as this is an admin console operation

    Keycloak keycloakAdmin =
        Keycloak.getInstance(
            AUTH_SERVER_URL, "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
    RealmResource master = keycloakAdmin.realms().realm("master");
    List<ComponentRepresentation> components =
        master.components().query(masterId, UserStorageProvider.class.getName());
    boolean found = false;
    for (ComponentRepresentation rep : components) {
      if (rep.getName().equals("bad-provider-id")) {
        found = true;
      }
    }
    Assert.assertTrue(found);

    master.components().component(component.getId()).remove();

    List<ComponentRepresentation> components2 =
        master.components().query(masterId, UserStorageProvider.class.getName());
    Assert.assertEquals(components.size() - 1, components2.size());
  }
  public void setRequiredActionEnabled(
      String realm, String requiredAction, boolean enabled, boolean defaultAction) {
    AuthenticationManagementResource managementResource = adminClient.realm(realm).flows();

    RequiredActionProviderRepresentation action =
        managementResource.getRequiredAction(requiredAction);
    action.setEnabled(enabled);
    action.setDefaultAction(defaultAction);

    managementResource.updateRequiredAction(requiredAction, action);
  }
  /**
   * 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);
  }
  public static void uploadSP(String AUTH_SERVER_URL) {
    try {
      Keycloak keycloak =
          Keycloak.getInstance(
              AUTH_SERVER_URL, "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID, null);
      RealmResource admin = keycloak.realm("demo");

      admin.toRepresentation();

      ClientRepresentation clientRep =
          admin.convertClientDescription(
              IOUtils.toString(
                  SamlAdapterTestStrategy.class.getResourceAsStream(
                      "/keycloak-saml/sp-metadata.xml")));
      Response response = admin.clients().create(clientRep);

      assertEquals(201, response.getStatus());

      keycloak.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  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);
  }
  @Before
  public void beforeAbstractKeycloakTest() throws Exception {
    SSLContext ssl = null;
    if ("true".equals(System.getProperty("auth.server.ssl.required"))) {
      ssl =
          getSSLContextWithTrustore(
              new File("src/test/resources/keystore/keycloak.truststore"), "secret");
    }
    adminClient =
        Keycloak.getInstance(
            AuthServerTestEnricher.getAuthServerContextRoot() + "/auth",
            MASTER,
            ADMIN,
            ADMIN,
            Constants.ADMIN_CLI_CLIENT_ID,
            null,
            ssl);

    getTestingClient();

    adminUser = createAdminUserRepresentation();

    setDefaultPageUriParameters();

    driverSettings();

    TestEventsLogger.setDriver(driver);

    if (!suiteContext.isAdminPasswordUpdated()) {
      log.debug("updating admin password");
      updateMasterAdminPassword();
      suiteContext.setAdminPasswordUpdated(true);
    }

    importTestRealms();

    oauth.init(adminClient, driver);
  }
 public RealmsResource realmsResouce() {
   return adminClient.realms();
 }
Beispiel #12
0
 public static UserRepresentation findUserWithAdminClient(Keycloak adminClient, String username) {
   return adminClient.realm("test").users().search(username, null, null, null, 0, 1).get(0);
 }
Beispiel #13
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();
    }
  }