/**
   * Delete execution
   *
   * @param execution Execution id
   */
  @Path("/executions/{executionId}")
  @DELETE
  @NoCache
  public void removeExecution(@PathParam("executionId") String execution) {
    auth.requireManage();

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
      session.getTransaction().setRollbackOnly();
      throw new NotFoundException("Illegal execution");
    }
    AuthenticationFlowModel parentFlow = getParentFlow(model);
    if (parentFlow.isBuiltIn()) {
      throw new BadRequestException("It is illegal to remove execution from a built in flow");
    }

    if (model.getFlowId() != null) {
      AuthenticationFlowModel nonTopLevelFlow = realm.getAuthenticationFlowById(model.getFlowId());
      realm.removeAuthenticationFlow(nonTopLevelFlow);
    }

    realm.removeAuthenticatorExecution(model);

    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success();
  }
  /**
   * 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;
  }
 protected UsernameLoginFailureModel getUserModel(KeycloakSession session, LoginEvent event) {
   RealmModel realm = session.getRealm(event.realmId);
   if (realm == null) return null;
   UsernameLoginFailureModel user = realm.getUserLoginFailure(event.username);
   if (user == null) return null;
   return user;
 }
  /**
   * Raise execution's priority
   *
   * @param execution Execution id
   */
  @Path("/executions/{executionId}/raise-priority")
  @POST
  @NoCache
  public void raisePriority(@PathParam("executionId") String execution) {
    auth.requireManage();

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
      session.getTransaction().setRollbackOnly();
      throw new NotFoundException("Illegal execution");
    }
    AuthenticationFlowModel parentFlow = getParentFlow(model);
    if (parentFlow.isBuiltIn()) {
      throw new BadRequestException("It is illegal to modify execution in a built in flow");
    }
    List<AuthenticationExecutionModel> executions = getSortedExecutions(parentFlow);
    AuthenticationExecutionModel previous = null;
    for (AuthenticationExecutionModel exe : executions) {
      if (exe.getId().equals(model.getId())) {
        break;
      }
      previous = exe;
    }
    if (previous == null) return;
    int tmp = previous.getPriority();
    previous.setPriority(model.getPriority());
    realm.updateAuthenticatorExecution(previous);
    model.setPriority(tmp);
    realm.updateAuthenticatorExecution(model);

    adminEvent.operation(OperationType.UPDATE).resourcePath(uriInfo).success();
  }
 /**
  * Endpoint for executing reset credentials flow. If code is null, a client session is created
  * with the account service as the client. Successful reset sends you to the account page. Note,
  * account service must be enabled.
  *
  * @param code
  * @param execution
  * @return
  */
 @Path(RESET_CREDENTIALS_PATH)
 @GET
 public Response resetCredentialsGET(
     @QueryParam("code") String code, @QueryParam("execution") String execution) {
   // we allow applications to link to reset credentials without going through OAuth or SAML
   // handshakes
   //
   if (code == null) {
     if (!realm.isResetPasswordAllowed()) {
       event.event(EventType.RESET_PASSWORD);
       event.error(Errors.NOT_ALLOWED);
       return ErrorPage.error(session, Messages.RESET_CREDENTIAL_NOT_ALLOWED);
     }
     // set up the account service as the endpoint to call.
     ClientModel client = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
     ClientSessionModel clientSession = session.sessions().createClientSession(realm, client);
     clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name());
     clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret());
     // clientSession.setNote(AuthenticationManager.END_AFTER_REQUIRED_ACTIONS, "true");
     clientSession.setAuthMethod(OIDCLoginProtocol.LOGIN_PROTOCOL);
     String redirectUri =
         Urls.accountBase(uriInfo.getBaseUri()).path("/").build(realm.getName()).toString();
     clientSession.setRedirectUri(redirectUri);
     clientSession.setAction(ClientSessionModel.Action.AUTHENTICATE.name());
     clientSession.setNote(ClientSessionCode.ACTION_KEY, KeycloakModelUtils.generateCodeSecret());
     clientSession.setNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
     clientSession.setNote(OIDCLoginProtocol.REDIRECT_URI_PARAM, redirectUri);
     clientSession.setNote(
         OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
     return processResetCredentials(null, clientSession, null);
   }
   return resetCredentials(code, execution);
 }
 public static void addOrUpdateGroupMapper(
     RealmModel realm,
     UserFederationProviderModel providerModel,
     LDAPGroupMapperMode mode,
     String descriptionAttrName,
     String... otherConfigOptions) {
   UserFederationMapperModel mapperModel =
       realm.getUserFederationMapperByName(providerModel.getId(), "groupsMapper");
   if (mapperModel != null) {
     mapperModel.getConfig().put(GroupMapperConfig.MODE, mode.toString());
     updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
     realm.updateUserFederationMapper(mapperModel);
   } else {
     String baseDn = providerModel.getConfig().get(LDAPConstants.BASE_DN);
     mapperModel =
         KeycloakModelUtils.createUserFederationMapperModel(
             "groupsMapper",
             providerModel.getId(),
             GroupLDAPFederationMapperFactory.PROVIDER_ID,
             GroupMapperConfig.GROUPS_DN,
             "ou=Groups," + baseDn,
             GroupMapperConfig.MAPPED_GROUP_ATTRIBUTES,
             descriptionAttrName,
             GroupMapperConfig.PRESERVE_GROUP_INHERITANCE,
             "true",
             GroupMapperConfig.MODE,
             mode.toString());
     updateGroupMapperConfigOptions(mapperModel, otherConfigOptions);
     realm.addUserFederationMapper(mapperModel);
   }
 }
  /**
   * Lower execution's priority
   *
   * @param execution Execution id
   */
  @Path("/executions/{executionId}/lower-priority")
  @POST
  @NoCache
  public void lowerPriority(@PathParam("executionId") String execution) {
    auth.requireManage();

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
      session.getTransaction().setRollbackOnly();
      throw new NotFoundException("Illegal execution");
    }
    AuthenticationFlowModel parentFlow = getParentFlow(model);
    if (parentFlow.isBuiltIn()) {
      throw new BadRequestException("It is illegal to modify execution in a built in flow");
    }
    List<AuthenticationExecutionModel> executions = getSortedExecutions(parentFlow);
    int i = 0;
    for (i = 0; i < executions.size(); i++) {
      if (executions.get(i).getId().equals(model.getId())) {
        break;
      }
    }
    if (i + 1 >= executions.size()) return;
    AuthenticationExecutionModel next = executions.get(i + 1);
    int tmp = model.getPriority();
    model.setPriority(next.getPriority());
    realm.updateAuthenticatorExecution(model);
    next.setPriority(tmp);
    realm.updateAuthenticatorExecution(next);

    adminEvent.operation(OperationType.UPDATE).resourcePath(uriInfo).success();
  }
Example #8
0
  private UserConsentModel toConsentModel(UserConsentEntity entity) {
    if (entity == null) {
      return null;
    }

    ClientModel client = realm.getClientById(entity.getClientId());
    if (client == null) {
      throw new ModelException("Client with id " + entity.getClientId() + " is not available");
    }
    UserConsentModel model = new UserConsentModel(client);

    Collection<UserConsentRoleEntity> grantedRoleEntities = entity.getGrantedRoles();
    if (grantedRoleEntities != null) {
      for (UserConsentRoleEntity grantedRole : grantedRoleEntities) {
        RoleModel grantedRoleModel = realm.getRoleById(grantedRole.getRoleId());
        if (grantedRoleModel != null) {
          model.addGrantedRole(grantedRoleModel);
        }
      }
    }

    Collection<UserConsentProtocolMapperEntity> grantedProtocolMapperEntities =
        entity.getGrantedProtocolMappers();
    if (grantedProtocolMapperEntities != null) {
      for (UserConsentProtocolMapperEntity grantedProtMapper : grantedProtocolMapperEntities) {
        ProtocolMapperModel protocolMapper =
            client.getProtocolMapperById(grantedProtMapper.getProtocolMapperId());
        model.addGrantedProtocolMapper(protocolMapper);
      }
    }

    return model;
  }
  /**
   * Update authentication executions of a flow
   *
   * @param flowAlias Flow alias
   * @param rep
   */
  @Path("/flows/{flowAlias}/executions")
  @PUT
  @NoCache
  @Consumes(MediaType.APPLICATION_JSON)
  public void updateExecutions(
      @PathParam("flowAlias") String flowAlias, AuthenticationExecutionInfoRepresentation rep) {
    auth.requireManage();

    AuthenticationFlowModel flow = realm.getFlowByAlias(flowAlias);
    if (flow == null) {
      logger.debug("flow not found: " + flowAlias);
      throw new NotFoundException("flow not found");
    }

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(rep.getId());
    if (model == null) {
      session.getTransaction().setRollbackOnly();
      throw new NotFoundException("Illegal execution");
    }
    if (!model.getRequirement().name().equals(rep.getRequirement())) {
      model.setRequirement(AuthenticationExecutionModel.Requirement.valueOf(rep.getRequirement()));
      realm.updateAuthenticatorExecution(model);
      adminEvent
          .operation(OperationType.UPDATE)
          .resourcePath(uriInfo)
          .representation(rep)
          .success();
    }
  }
Example #10
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);
    }
  }
  /**
   * Create a new authentication flow
   *
   * @param flow Authentication flow representation
   * @return
   */
  @Path("/flows")
  @POST
  @NoCache
  @Consumes(MediaType.APPLICATION_JSON)
  public Response createFlow(AuthenticationFlowRepresentation flow) {
    auth.requireManage();

    if (flow.getAlias() == null || flow.getAlias().isEmpty()) {
      return ErrorResponse.exists("Failed to create flow with empty alias name");
    }

    if (realm.getFlowByAlias(flow.getAlias()) != null) {
      return ErrorResponse.exists("Flow " + flow.getAlias() + " already exists");
    }

    AuthenticationFlowModel createdModel =
        realm.addAuthenticationFlow(RepresentationToModel.toModel(flow));

    flow.setId(createdModel.getId());
    adminEvent
        .operation(OperationType.CREATE)
        .resourcePath(uriInfo, createdModel.getId())
        .representation(flow)
        .success();
    return Response.status(201).build();
  }
  /**
   * Copy existing authentication flow under a new name
   *
   * <p>The new name is given as 'newName' attribute of the passed JSON object
   *
   * @param flowAlias Name of the existing authentication flow
   * @param data JSON containing 'newName' attribute
   */
  @Path("/flows/{flowAlias}/copy")
  @POST
  @NoCache
  @Consumes(MediaType.APPLICATION_JSON)
  public Response copy(@PathParam("flowAlias") String flowAlias, Map<String, String> data) {
    auth.requireManage();

    String newName = data.get("newName");
    if (realm.getFlowByAlias(newName) != null) {
      return Response.status(Response.Status.CONFLICT).build();
    }

    AuthenticationFlowModel flow = realm.getFlowByAlias(flowAlias);
    if (flow == null) {
      logger.debug("flow not found: " + flowAlias);
      return Response.status(NOT_FOUND).build();
    }
    AuthenticationFlowModel copy = new AuthenticationFlowModel();
    copy.setAlias(newName);
    copy.setDescription(flow.getDescription());
    copy.setProviderId(flow.getProviderId());
    copy.setBuiltIn(false);
    copy.setTopLevel(flow.isTopLevel());
    copy = realm.addAuthenticationFlow(copy);
    copy(newName, flow, copy);

    data.put("id", copy.getId());
    adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(data).success();

    return Response.status(201).build();
  }
Example #13
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");
    }
  }
Example #14
0
 public static String getIDPMetadataDescriptor(
     UriInfo uriInfo, KeycloakSession session, RealmModel realm) throws IOException {
   InputStream is = SamlService.class.getResourceAsStream("/idp-metadata-template.xml");
   String template = StreamUtil.readString(is);
   template =
       template.replace(
           "${idp.entityID}",
           RealmsResource.realmBaseUrl(uriInfo).build(realm.getName()).toString());
   template =
       template.replace(
           "${idp.sso.HTTP-POST}",
           RealmsResource.protocolUrl(uriInfo)
               .build(realm.getName(), SamlProtocol.LOGIN_PROTOCOL)
               .toString());
   template =
       template.replace(
           "${idp.sso.HTTP-Redirect}",
           RealmsResource.protocolUrl(uriInfo)
               .build(realm.getName(), SamlProtocol.LOGIN_PROTOCOL)
               .toString());
   template =
       template.replace(
           "${idp.sls.HTTP-POST}",
           RealmsResource.protocolUrl(uriInfo)
               .build(realm.getName(), SamlProtocol.LOGIN_PROTOCOL)
               .toString());
   template =
       template.replace(
           "${idp.signing.certificate}",
           PemUtils.encodeCertificate(session.keys().getActiveKey(realm).getCertificate()));
   return template;
 }
Example #15
0
 protected AccessToken initToken(
     RealmModel realm,
     ClientModel client,
     UserModel user,
     UserSessionModel session,
     ClientSessionModel clientSession) {
   AccessToken token = new AccessToken();
   if (clientSession != null) token.clientSession(clientSession.getId());
   token.id(KeycloakModelUtils.generateId());
   token.subject(user.getId());
   token.audience(client.getClientId());
   token.issuedNow();
   token.issuedFor(client.getClientId());
   token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
   if (session != null) {
     token.setSessionState(session.getId());
   }
   if (realm.getAccessTokenLifespan() > 0) {
     token.expiration(Time.currentTime() + realm.getAccessTokenLifespan());
   }
   Set<String> allowedOrigins = client.getWebOrigins();
   if (allowedOrigins != null) {
     token.setAllowedOrigins(allowedOrigins);
   }
   return token;
 }
Example #16
0
  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);
  }
Example #17
0
 @Path("sessions/{session}")
 @DELETE
 public void deleteSession(@PathParam("session") String sessionId) {
   UserSessionModel session = realm.getUserSession(sessionId);
   if (session == null) throw new NotFoundException("Sesssion not found");
   realm.removeUserSession(session);
   new ResourceAdminManager().logoutSession(uriInfo.getRequestUri(), realm, session.getId());
 }
  /**
   * Update the top-level information of the realm
   *
   * <p>Any user, roles or client information in the representation will be ignored. This will only
   * update top-level attributes of the realm.
   *
   * @param rep
   * @return
   */
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response updateRealm(final RealmRepresentation rep) {
    auth.requireManage();

    logger.debug("updating realm: " + realm.getName());

    if (Config.getAdminRealm().equals(realm.getName())
        && (rep.getRealm() != null && !rep.getRealm().equals(Config.getAdminRealm()))) {
      return ErrorResponse.error("Can't rename master realm", Status.BAD_REQUEST);
    }

    try {
      if (!Constants.GENERATE.equals(rep.getPublicKey())
          && (rep.getPrivateKey() != null && rep.getPublicKey() != null)) {
        try {
          KeyPairVerifier.verify(rep.getPrivateKey(), rep.getPublicKey());
        } catch (VerificationException e) {
          return ErrorResponse.error(e.getMessage(), Status.BAD_REQUEST);
        }
      }

      if (!Constants.GENERATE.equals(rep.getPublicKey()) && (rep.getCertificate() != null)) {
        try {
          X509Certificate cert = PemUtils.decodeCertificate(rep.getCertificate());
          if (cert == null) {
            return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
          }
        } catch (Exception e) {
          return ErrorResponse.error("Failed to decode certificate", Status.BAD_REQUEST);
        }
      }

      RepresentationToModel.updateRealm(rep, realm, session);

      // Refresh periodic sync tasks for configured federationProviders
      List<UserStorageProviderModel> federationProviders = realm.getUserStorageProviders();
      UserStorageSyncManager usersSyncManager = new UserStorageSyncManager();
      for (final UserStorageProviderModel fedProvider : federationProviders) {
        usersSyncManager.notifyToRefreshPeriodicSync(session, realm, fedProvider, false);
      }

      adminEvent
          .operation(OperationType.UPDATE)
          .representation(StripSecretsUtils.strip(rep))
          .success();
      return Response.noContent().build();
    } catch (PatternSyntaxException e) {
      return ErrorResponse.error(
          "Specified regex pattern(s) is invalid.", Response.Status.BAD_REQUEST);
    } catch (ModelDuplicateException e) {
      return ErrorResponse.exists("Realm with same name exists");
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      return ErrorResponse.error("Failed to update realm", Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
Example #19
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");
  }
Example #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);
              }
            }
Example #21
0
  /**
   * Impersonate the user
   *
   * @param id User id
   * @return
   */
  @Path("{id}/impersonation")
  @POST
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public Map<String, Object> impersonate(final @PathParam("id") String id) {
    auth.init(RealmAuth.Resource.IMPERSONATION);
    auth.requireManage();
    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      throw new NotFoundException("User not found");
    }
    RealmModel authenticatedRealm = auth.getAuth().getRealm();
    // if same realm logout before impersonation
    boolean sameRealm = false;
    if (authenticatedRealm.getId().equals(realm.getId())) {
      sameRealm = true;
      UserSessionModel userSession =
          session
              .sessions()
              .getUserSession(authenticatedRealm, auth.getAuth().getToken().getSessionState());
      AuthenticationManager.expireIdentityCookie(realm, uriInfo, clientConnection);
      AuthenticationManager.expireRememberMeCookie(realm, uriInfo, clientConnection);
      AuthenticationManager.backchannelLogout(
          session, authenticatedRealm, userSession, uriInfo, clientConnection, headers, true);
    }
    EventBuilder event = new EventBuilder(realm, session, clientConnection);

    UserSessionModel userSession =
        session
            .sessions()
            .createUserSession(
                realm,
                user,
                user.getUsername(),
                clientConnection.getRemoteAddr(),
                "impersonate",
                false,
                null,
                null);
    AuthenticationManager.createLoginCookie(
        realm, userSession.getUser(), userSession, uriInfo, clientConnection);
    URI redirect = AccountService.accountServiceApplicationPage(uriInfo).build(realm.getName());
    Map<String, Object> result = new HashMap<>();
    result.put("sameRealm", sameRealm);
    result.put("redirect", redirect.toString());
    event
        .event(EventType.IMPERSONATE)
        .session(userSession)
        .user(user)
        .detail(Details.IMPERSONATOR_REALM, authenticatedRealm.getName())
        .detail(Details.IMPERSONATOR, auth.getAuth().getUser().getUsername())
        .success();

    return result;
  }
Example #22
0
  private ClientSessionModel createClientSession(
      UserModel user, String redirectUri, String clientId) {

    if (!user.isEnabled()) {
      throw new WebApplicationException(
          ErrorResponse.error("User is disabled", Response.Status.BAD_REQUEST));
    }

    if (redirectUri != null && clientId == null) {
      throw new WebApplicationException(
          ErrorResponse.error("Client id missing", Response.Status.BAD_REQUEST));
    }

    if (clientId == null) {
      clientId = Constants.ACCOUNT_MANAGEMENT_CLIENT_ID;
    }

    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null || !client.isEnabled()) {
      throw new WebApplicationException(
          ErrorResponse.error(clientId + " not enabled", Response.Status.BAD_REQUEST));
    }

    String redirect;
    if (redirectUri != null) {
      redirect = RedirectUtils.verifyRedirectUri(uriInfo, redirectUri, realm, client);
      if (redirect == null) {
        throw new WebApplicationException(
            ErrorResponse.error("Invalid redirect uri.", Response.Status.BAD_REQUEST));
      }
    } else {
      redirect = Urls.accountBase(uriInfo.getBaseUri()).path("/").build(realm.getName()).toString();
    }

    UserSessionModel userSession =
        session
            .sessions()
            .createUserSession(
                realm,
                user,
                user.getUsername(),
                clientConnection.getRemoteAddr(),
                "form",
                false,
                null,
                null);
    // audit.session(userSession);
    ClientSessionModel clientSession = session.sessions().createClientSession(realm, client);
    clientSession.setAuthMethod(OIDCLoginProtocol.LOGIN_PROTOCOL);
    clientSession.setRedirectUri(redirect);
    clientSession.setUserSession(userSession);

    return clientSession;
  }
Example #23
0
  @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");
  }
Example #24
0
  public String toJBossSubsystemConfig(
      RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<secure-deployment name=\"WAR MODULE NAME.war\">\n");
    buffer.append("    <realm>").append(realmModel.getName()).append("</realm>\n");
    buffer
        .append("    <auth-server-url>")
        .append(baseUri.toString())
        .append("</auth-server-url>\n");
    if (clientModel.isBearerOnly()) {
      buffer.append("    <bearer-only>true</bearer-only>\n");

    } else if (clientModel.isPublicClient()) {
      buffer.append("    <public-client>true</public-client>\n");
    }
    buffer
        .append("    <ssl-required>")
        .append(realmModel.getSslRequired().name())
        .append("</ssl-required>\n");
    buffer.append("    <resource>").append(clientModel.getClientId()).append("</resource>\n");
    String cred = clientModel.getSecret();
    if (showClientCredentialsAdapterConfig(clientModel)) {
      Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
      for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) {
        buffer.append("    <credential name=\"" + entry.getKey() + "\">");

        Object value = entry.getValue();
        if (value instanceof Map) {
          buffer.append("\n");
          Map<String, Object> asMap = (Map<String, Object>) value;
          for (Map.Entry<String, Object> credEntry : asMap.entrySet()) {
            buffer.append(
                "        <"
                    + credEntry.getKey()
                    + ">"
                    + credEntry.getValue().toString()
                    + "</"
                    + credEntry.getKey()
                    + ">\n");
          }
          buffer.append("    </credential>\n");
        } else {
          buffer.append(value.toString()).append("</credential>\n");
        }
      }
    }
    if (clientModel.getRoles().size() > 0) {
      buffer.append("    <use-resource-role-mappings>true</use-resource-role-mappings>\n");
    }
    buffer.append("</secure-deployment>\n");
    return buffer.toString();
  }
  protected void updateProviderEditMode(UserFederationProvider.EditMode editMode) {
    KeycloakRule keycloakRule = getKeycloakRule();

    KeycloakSession session = keycloakRule.startSession();
    try {
      RealmModel realm = session.realms().getRealm("test");
      UserFederationProviderModel kerberosProviderModel = realm.getUserFederationProviders().get(0);
      kerberosProviderModel.getConfig().put(LDAPConstants.EDIT_MODE, editMode.toString());
      realm.updateUserFederationProvider(kerberosProviderModel);
    } finally {
      keycloakRule.stopSession(session, true);
    }
  }
  /**
   * Delete required action
   *
   * @param alias Alias of required action
   */
  @Path("required-actions/{alias}")
  @DELETE
  public void removeRequiredAction(@PathParam("alias") String alias) {
    auth.requireManage();

    RequiredActionProviderModel model = realm.getRequiredActionProviderByAlias(alias);
    if (model == null) {
      throw new NotFoundException("Failed to find required action.");
    }
    realm.removeRequiredActionProvider(model);

    adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success();
  }
Example #27
0
 /**
  * Convenience path to master realm admin console
  *
  * @return
  */
 @GET
 public Response masterRealmAdminConsoleRedirect() {
   RealmModel master = new RealmManager(session).getKeycloakAdminstrationRealm();
   return Response.status(302)
       .location(
           uriInfo
               .getBaseUriBuilder()
               .path(AdminRoot.class)
               .path(AdminRoot.class, "getAdminConsole")
               .path("/")
               .build(master.getName()))
       .build();
 }
Example #28
0
  /**
   * Send a update account email to the user
   *
   * <p>An email contains a link the user can click to perform a set of required actions. The
   * redirectUri and clientId parameters are optional. The default for the redirect is the account
   * client.
   *
   * @param id User is
   * @param redirectUri Redirect uri
   * @param clientId Client id
   * @param actions required actions the user needs to complete
   * @return
   */
  @Path("{id}/execute-actions-email")
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response executeActionsEmail(
      @PathParam("id") String id,
      @QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri,
      @QueryParam(OIDCLoginProtocol.CLIENT_ID_PARAM) String clientId,
      List<String> actions) {
    auth.requireManage();

    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      return ErrorResponse.error("User not found", Response.Status.NOT_FOUND);
    }

    if (user.getEmail() == null) {
      return ErrorResponse.error("User email missing", Response.Status.BAD_REQUEST);
    }

    ClientSessionModel clientSession = createClientSession(user, redirectUri, clientId);
    for (String action : actions) {
      clientSession.addRequiredAction(action);
    }
    ClientSessionCode accessCode = new ClientSessionCode(realm, clientSession);
    accessCode.setAction(ClientSessionModel.Action.EXECUTE_ACTIONS.name());

    try {
      UriBuilder builder = Urls.executeActionsBuilder(uriInfo.getBaseUri());
      builder.queryParam("key", accessCode.getCode());

      String link = builder.build(realm.getName()).toString();
      long expiration = TimeUnit.SECONDS.toMinutes(realm.getAccessCodeLifespanUserAction());

      this.session
          .getProvider(EmailTemplateProvider.class)
          .setRealm(realm)
          .setUser(user)
          .sendExecuteActions(link, expiration);

      // audit.user(user).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID,
      // accessCode.getCodeId()).success();

      adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success();

      return Response.ok().build();
    } catch (EmailException e) {
      logger.failedToSendActionsEmail(e);
      return ErrorResponse.error(
          "Failed to send execute actions email", Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
Example #29
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();
  }
Example #30
0
  public static void syncRolesFromLDAP(
      RealmModel realm,
      LDAPFederationProvider ldapProvider,
      UserFederationProviderModel providerModel) {
    UserFederationMapperModel mapperModel =
        realm.getUserFederationMapperByName(providerModel.getId(), "realmRolesMapper");
    RoleLDAPFederationMapper roleMapper = getRoleMapper(mapperModel, ldapProvider, realm);

    roleMapper.syncDataFromFederationProviderToKeycloak();

    mapperModel = realm.getUserFederationMapperByName(providerModel.getId(), "financeRolesMapper");
    roleMapper = getRoleMapper(mapperModel, ldapProvider, realm);
    roleMapper.syncDataFromFederationProviderToKeycloak();
  }