コード例 #1
0
  private static String createAdminToken(String username, String realm) {
    KeycloakSession session = keycloakRule.startSession();
    try {
      RealmManager manager = new RealmManager(session);

      RealmModel adminRealm = manager.getRealm(realm);
      ClientModel adminConsole = adminRealm.getClientByClientId(Constants.ADMIN_CLI_CLIENT_ID);
      TokenManager tm = new TokenManager();
      UserModel admin = session.users().getUserByUsername(username, adminRealm);
      ClientSessionModel clientSession =
          session.sessions().createClientSession(adminRealm, adminConsole);
      clientSession.setNote(OIDCLoginProtocol.ISSUER, "http://localhost:8081/auth/realms/" + realm);
      UserSessionModel userSession =
          session
              .sessions()
              .createUserSession(adminRealm, admin, "admin", null, "form", false, null, null);
      AccessToken token =
          tm.createClientAccessToken(
              session,
              tm.getAccess(null, true, adminConsole, admin),
              adminRealm,
              adminConsole,
              admin,
              userSession,
              clientSession);
      return tm.encodeToken(adminRealm, token);
    } finally {
      keycloakRule.stopSession(session, true);
    }
  }
コード例 #2
0
  /**
   * Import a realm
   *
   * <p>Imports a realm from a full representation of that realm. Realm name must be unique.
   *
   * @param uriInfo
   * @param rep JSON representation of the realm
   * @return
   */
  @POST
  @Consumes(MediaType.APPLICATION_JSON)
  public Response importRealm(@Context final UriInfo uriInfo, final RealmRepresentation rep) {
    RealmManager realmManager = new RealmManager(session);
    realmManager.setContextPath(keycloak.getContextPath());
    if (!auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())) {
      throw new ForbiddenException();
    }
    if (!auth.hasRealmRole(AdminRoles.CREATE_REALM)) {
      throw new ForbiddenException();
    }

    logger.debugv("importRealm: {0}", rep.getRealm());

    try {
      RealmModel realm = realmManager.importRealm(rep);
      grantPermissionsToRealmCreator(realm);

      URI location = AdminRoot.realmsUrl(uriInfo).path(realm.getName()).build();
      logger.debugv("imported realm success, sending back: {0}", location.toString());

      return Response.created(location).build();
    } catch (ModelDuplicateException e) {
      return ErrorResponse.exists("Realm with same name exists");
    }
  }
コード例 #3
0
  protected void assertUser(
      String expectedUsername,
      String expectedEmail,
      String expectedFirstname,
      String expectedLastname,
      boolean updateProfileActionExpected) {
    KeycloakRule keycloakRule = getKeycloakRule();

    KeycloakSession session = keycloakRule.startSession();
    try {
      RealmManager manager = new RealmManager(session);
      RealmModel appRealm = manager.getRealm("test");

      UserModel user = session.users().getUserByUsername(expectedUsername, appRealm);
      Assert.assertNotNull(user);
      Assert.assertEquals(user.getEmail(), expectedEmail);
      Assert.assertEquals(user.getFirstName(), expectedFirstname);
      Assert.assertEquals(user.getLastName(), expectedLastname);

      if (updateProfileActionExpected) {
        Assert.assertEquals(
            UserModel.RequiredAction.UPDATE_PROFILE.toString(),
            user.getRequiredActions().iterator().next());
      } else {
        Assert.assertTrue(user.getRequiredActions().isEmpty());
      }
    } finally {
      keycloakRule.stopSession(session, true);
    }
  }
コード例 #4
0
  /**
   * Base path for the admin REST API for one particular realm.
   *
   * @param headers
   * @param name realm name (not id!)
   * @return
   */
  @Path("{realm}")
  public RealmAdminResource getRealmAdmin(
      @Context final HttpHeaders headers, @PathParam("realm") final String name) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(name);
    if (realm == null) throw new NotFoundException("Realm not found.");

    if (!auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())
        && !auth.getRealm().equals(realm)) {
      throw new ForbiddenException();
    }
    RealmAuth realmAuth;

    if (auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())) {
      realmAuth = new RealmAuth(auth, realm.getMasterAdminClient());
    } else {
      realmAuth =
          new RealmAuth(
              auth, realm.getClientByClientId(realmManager.getRealmAdminClientId(auth.getRealm())));
    }

    AdminEventBuilder adminEvent = new AdminEventBuilder(realm, auth, session, clientConnection);
    session.getContext().setRealm(realm);

    RealmAdminResource adminResource =
        new RealmAdminResource(realmAuth, realm, tokenManager, adminEvent);
    ResteasyProviderFactory.getInstance().injectProperties(adminResource);
    // resourceContext.initResource(adminResource);
    return adminResource;
  }
コード例 #5
0
ファイル: AdminRoot.java プロジェクト: appcube/keycloak
  protected AdminAuth authenticateRealmAdminRequest(HttpHeaders headers) {
    String tokenString = authManager.extractAuthorizationHeaderToken(headers);
    if (tokenString == null) throw new UnauthorizedException("Bearer");
    JWSInput input = new JWSInput(tokenString);
    AccessToken token;
    try {
      token = input.readJsonContent(AccessToken.class);
    } catch (IOException e) {
      throw new UnauthorizedException("Bearer token format error");
    }
    String realmName = token.getAudience();
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealmByName(realmName);
    if (realm == null) {
      throw new UnauthorizedException("Unknown realm in token");
    }
    AuthenticationManager.AuthResult authResult =
        authManager.authenticateBearerToken(session, realm, uriInfo, clientConnection, headers);
    if (authResult == null) {
      logger.debug("Token not valid");
      throw new UnauthorizedException("Bearer");
    }

    ClientModel client = realm.findClient(token.getIssuedFor());
    if (client == null) {
      throw new NotFoundException("Could not find client for authorization");
    }

    return new AdminAuth(realm, authResult.getToken(), authResult.getUser(), client);
  }
コード例 #6
0
  @Test
  public void install2() throws Exception {
    RealmManager manager = realmManager;
    RealmRepresentation rep = AbstractModelTest.loadJson("model/testrealm-demo.json");
    rep.setId("demo");
    RealmModel realm = manager.importRealm(rep);

    Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction());
    verifyRequiredCredentials(realm.getRequiredCredentials(), "password");
  }
コード例 #7
0
ファイル: ImportTest.java プロジェクト: jeroenr/keycloak
  @Test
  public void install2() throws Exception {
    RealmManager manager = realmManager;
    RealmRepresentation rep = AbstractModelTest.loadJson("testrealm-demo.json");
    RealmModel realm = manager.createRealm("demo", rep.getRealm());
    manager.importRealm(rep, realm);

    Assert.assertFalse(realm.isUpdateProfileOnInitialSocialLogin());
    Assert.assertEquals(600, realm.getAccessCodeLifespanUserAction());
    verifyRequiredCredentials(realm.getRequiredCredentials(), "password");
  }
コード例 #8
0
  @Path("{id}")
  public RealmAdminResource getRealmAdmin(
      @Context final HttpHeaders headers, @PathParam("id") final String id) {
    RealmManager realmManager = new RealmManager(session);
    RealmModel realm = realmManager.getRealm(id);
    if (realm == null) throw new NotFoundException();

    RealmAdminResource adminResource = new RealmAdminResource(admin, realm);
    resourceContext.initResource(adminResource);
    return adminResource;
  }
コード例 #9
0
 @GET
 @NoCache
 @Produces("application/json")
 public List<RealmRepresentation> getRealms() {
   logger.debug(("getRealms()"));
   RealmManager realmManager = new RealmManager(session);
   List<RealmModel> realms = session.getRealms(admin);
   List<RealmRepresentation> reps = new ArrayList<RealmRepresentation>();
   for (RealmModel realm : realms) {
     reps.add(realmManager.toRepresentation(realm));
   }
   return reps;
 }
コード例 #10
0
  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public Response uploadRealm(MultipartFormDataInput input) throws IOException {
    Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
    List<InputPart> inputParts = uploadForm.get("file");

    RealmManager realmManager = new RealmManager(session);
    for (InputPart inputPart : inputParts) {
      inputPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
      RealmRepresentation rep = inputPart.getBody(new GenericType<RealmRepresentation>() {});
      realmManager.importRealm(rep, admin);
    }
    return Response.noContent().build();
  }
コード例 #11
0
  @POST
  @Consumes("application/json")
  public Response importRealm(@Context final UriInfo uriInfo, final RealmRepresentation rep) {
    logger.debug("importRealm: {0}", rep.getRealm());
    RealmManager realmManager = new RealmManager(session);
    if (realmManager.getRealm(rep.getRealm()) != null) {
      return Flows.errors().exists("Realm " + rep.getRealm() + " already exists");
    }

    RealmModel realm = realmManager.importRealm(rep, admin);
    URI location = realmUrl(uriInfo).build(realm.getId());
    logger.debug("imported realm success, sending back: {0}", location.toString());
    return Response.created(location).build();
  }
コード例 #12
0
  protected void setupKeycloak() {
    KeycloakSession session = server.getKeycloakSessionFactory().createSession();
    session.getTransaction().begin();

    try {
      RealmManager manager = new RealmManager(session);

      RealmModel adminstrationRealm = manager.getRealm(Config.getAdminRealm());

      configure(manager, adminstrationRealm);

      session.getTransaction().commit();
    } finally {
      session.close();
    }
  }
コード例 #13
0
ファイル: AdminRoot.java プロジェクト: appcube/keycloak
 protected RealmModel locateRealm(String name, RealmManager realmManager) {
   RealmModel realm = realmManager.getRealmByName(name);
   if (realm == null) {
     throw new NotFoundException("Realm " + name + " not found");
   }
   return realm;
 }
コード例 #14
0
 public static RealmModel baseAdapterTestInitialization(
     KeycloakSession session, RealmManager manager, RealmModel adminRealm, Class<?> clazz) {
   RealmRepresentation representation =
       KeycloakServer.loadJson(
           clazz.getResourceAsStream("/keycloak-saml/testsaml.json"), RealmRepresentation.class);
   RealmModel demoRealm = manager.importRealm(representation);
   return demoRealm;
 }
コード例 #15
0
ファイル: TomcatTest.java プロジェクト: hoangbt/keycloak
 @Override
 protected void configure(
     KeycloakSession session, RealmManager manager, RealmModel adminRealm) {
   RealmRepresentation representation =
       KeycloakServer.loadJson(
           getClass().getResourceAsStream("/adapter-test/demorealm.json"),
           RealmRepresentation.class);
   RealmModel realm = manager.importRealm(representation);
 }
コード例 #16
0
  protected void removeAllUsers() {
    KeycloakRule keycloakRule = getKeycloakRule();

    KeycloakSession session = keycloakRule.startSession();
    try {
      RealmManager manager = new RealmManager(session);

      RealmModel appRealm = manager.getRealm("test");
      List<UserModel> users = session.userStorage().getUsers(appRealm, true);
      for (UserModel user : users) {
        if (!user.getUsername().equals(AssertEvents.DEFAULT_USERNAME)) {
          session.userStorage().removeUser(appRealm, user);
        }
      }

      Assert.assertEquals(1, session.userStorage().getUsers(appRealm, true).size());
    } finally {
      keycloakRule.stopSession(session, true);
    }
  }
コード例 #17
0
ファイル: AccountTest.java プロジェクト: niuhw/keycloak
            @Override
            public void config(
                RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
              UserModel user =
                  manager.getSession().users().getUserByUsername("test-user@localhost", appRealm);

              ClientModel accountApp =
                  appRealm
                      .getClientNameMap()
                      .get(org.keycloak.models.Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);

              UserModel user2 =
                  manager.getSession().users().addUser(appRealm, "test-user-no-access@localhost");
              user2.setEnabled(true);
              user2.setEmail("test-user-no-access@localhost");
              for (String r : accountApp.getDefaultRoles()) {
                user2.deleteRoleMapping(accountApp.getRole(r));
              }
              UserCredentialModel creds = new UserCredentialModel();
              creds.setType(CredentialRepresentation.PASSWORD);
              creds.setValue("password");
              user2.updateCredential(creds);
            }
コード例 #18
0
  /**
   * Get accessible realms
   *
   * <p>Returns a list of accessible realms. The list is filtered based on what realms the caller is
   * allowed to view.
   *
   * @return
   */
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public List<RealmRepresentation> getRealms() {
    RealmManager realmManager = new RealmManager(session);
    List<RealmRepresentation> reps = new ArrayList<RealmRepresentation>();
    if (auth.getRealm().equals(realmManager.getKeycloakAdminstrationRealm())) {
      List<RealmModel> realms = session.realms().getRealms();
      for (RealmModel realm : realms) {
        addRealmRep(reps, realm, realm.getMasterAdminClient());
      }
    } else {
      ClientModel adminApp =
          auth.getRealm().getClientByClientId(realmManager.getRealmAdminClientId(auth.getRealm()));
      addRealmRep(reps, auth.getRealm(), adminApp);
    }

    if (reps.isEmpty()) {
      throw new ForbiddenException();
    }

    logger.debug(("getRealms()"));
    return reps;
  }
コード例 #19
0
  private static String createToken() {
    KeycloakSession session = keycloakRule.startSession();
    try {
      RealmManager manager = new RealmManager(session);

      RealmModel adminRealm = manager.getRealm(Config.getAdminRealm());
      ApplicationModel adminConsole =
          adminRealm.getApplicationByName(Constants.ADMIN_CONSOLE_APPLICATION);
      TokenManager tm = new TokenManager();
      UserModel admin = session.users().getUserByUsername("admin", adminRealm);
      UserSessionModel userSession =
          session.sessions().createUserSession(adminRealm, admin, "admin", null, "form", false);
      AccessToken token =
          tm.createClientAccessToken(
              tm.getAccess(null, adminConsole, admin),
              adminRealm,
              adminConsole,
              admin,
              userSession);
      return tm.encodeToken(adminRealm, token);
    } finally {
      keycloakRule.stopSession(session, true);
    }
  }
コード例 #20
0
            @Override
            public void config(
                RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
              impersonatedUserId =
                  manager
                      .getSession()
                      .users()
                      .getUserByUsername("test-user@localhost", appRealm)
                      .getId();
              {
                UserModel masterImpersonator =
                    manager.getSession().users().addUser(adminstrationRealm, "master-impersonator");
                masterImpersonator.setEnabled(true);
                ClientModel adminRealmClient =
                    adminstrationRealm.getClientByClientId(
                        KeycloakModelUtils.getMasterRealmAdminApplicationClientId(
                            appRealm.getName()));
                RoleModel masterImpersonatorRole =
                    adminRealmClient.getRole(ImpersonationConstants.IMPERSONATION_ROLE);
                masterImpersonator.grantRole(masterImpersonatorRole);
              }
              {
                UserModel masterBadImpersonator =
                    manager
                        .getSession()
                        .users()
                        .addUser(adminstrationRealm, "master-bad-impersonator");
                masterBadImpersonator.setEnabled(true);
              }

              {
                UserModel impersonator =
                    manager.getSession().users().addUser(appRealm, "impersonator");
                impersonator.setEnabled(true);
                ClientModel appRealmClient =
                    appRealm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
                RoleModel realmImpersonatorRole =
                    appRealmClient.getRole(ImpersonationConstants.IMPERSONATION_ROLE);
                impersonator.grantRole(realmImpersonatorRole);
              }
              {
                UserModel impersonator =
                    manager.getSession().users().addUser(appRealm, "realm-admin");
                impersonator.setEnabled(true);
                ClientModel appRealmClient =
                    appRealm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
                RoleModel realmImpersonatorRole = appRealmClient.getRole(AdminRoles.REALM_ADMIN);
                impersonator.grantRole(realmImpersonatorRole);
              }
              {
                UserModel badimpersonator =
                    manager.getSession().users().addUser(appRealm, "bad-impersonator");
                badimpersonator.setEnabled(true);
              }
            }
コード例 #21
0
            @Override
            public void config(
                RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
              UserModel user = manager.getSession().users().addUser(appRealm, "login-test");
              user.setEmail("*****@*****.**");
              user.setEnabled(true);

              userId = user.getId();

              UserCredentialModel creds = new UserCredentialModel();
              creds.setType(CredentialRepresentation.PASSWORD);
              creds.setValue("password");

              user.updateCredential(creds);
              appRealm.setEventsListeners(Collections.singleton("dummy"));
            }
コード例 #22
0
ファイル: DemoApplication.java プロジェクト: kpiwko/keycloak
 public void install(RealmManager manager) {
   RealmRepresentation rep = loadJson("META-INF/testrealm.json");
   RealmModel realm = manager.createRealm("demo", rep.getRealm());
   manager.importRealm(rep, realm);
 }