Esempio n. 1
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;
 }
Esempio n. 2
0
 /**
  * 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);
 }
  /**
   * 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);
    }
  }
Esempio n. 4
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;
  }
 @Override
 public Response keycloakInitiatedBrowserLogout(
     UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
   if (getConfig().getLogoutUrl() == null || getConfig().getLogoutUrl().trim().equals(""))
     return null;
   String idToken = userSession.getNote(FEDERATED_ID_TOKEN);
   if (idToken != null && getConfig().isBackchannelSupported()) {
     backchannelLogout(userSession, idToken);
     return null;
   } else {
     String sessionId = userSession.getId();
     UriBuilder logoutUri =
         UriBuilder.fromUri(getConfig().getLogoutUrl()).queryParam("state", sessionId);
     if (idToken != null) logoutUri.queryParam("id_token_hint", idToken);
     String redirect =
         RealmsResource.brokerUrl(uriInfo)
             .path(IdentityBrokerService.class, "getEndpoint")
             .path(OIDCEndpoint.class, "logoutResponse")
             .build(realm.getName(), getConfig().getAlias())
             .toString();
     logoutUri.queryParam("post_logout_redirect_uri", redirect);
     Response response = Response.status(302).location(logoutUri.build()).build();
     return response;
   }
 }
Esempio n. 6
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");
    }
  }
  @PUT
  @Consumes("application/json")
  public void updateRealm(final RealmRepresentation rep) {
    auth.requireManage();

    logger.debug("updating realm: " + realm.getName());
    new RealmManager(session).updateRealm(rep, realm);
  }
Esempio n. 8
0
  /**
   * Update the events provider
   *
   * <p>Change the events provider and/or its configuration
   *
   * @param rep
   */
  @PUT
  @Path("events/config")
  @Consumes(MediaType.APPLICATION_JSON)
  public void updateRealmEventsConfig(final RealmEventsConfigRepresentation rep) {
    auth.init(RealmAuth.Resource.EVENTS).requireManage();

    logger.debug("updating realm events config: " + realm.getName());
    new RealmManager(session).updateRealmEventsConfig(rep, realm);
  }
Esempio n. 9
0
  @PUT
  @Path("audit")
  @Consumes("application/json")
  public void updateRealmAudit(final RealmAuditRepresentation rep) {
    auth.init(RealmAuth.Resource.AUDIT).requireManage();

    logger.debug("updating realm audit: " + realm.getName());
    new RealmManager(session).updateRealmAudit(rep, realm);
  }
Esempio n. 10
0
 protected void addRealmRep(
     List<RealmRepresentation> reps, RealmModel realm, ClientModel realmManagementClient) {
   if (auth.hasAppRole(realmManagementClient, AdminRoles.VIEW_REALM)) {
     reps.add(ModelToRepresentation.toRepresentation(realm, false));
   } else if (auth.hasOneOfAppRole(realmManagementClient, AdminRoles.ALL_REALM_ROLES)) {
     RealmRepresentation rep = new RealmRepresentation();
     rep.setRealm(realm.getName());
     reps.add(rep);
   }
 }
Esempio n. 11
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);
              }
            }
Esempio n. 12
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;
  }
Esempio n. 13
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();
  }
Esempio n. 14
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();
 }
Esempio n. 15
0
  @PUT
  @Consumes("application/json")
  public Response updateRealm(final RealmRepresentation rep) {
    auth.requireManage();

    logger.debug("updating realm: " + realm.getName());
    try {
      new RealmManager(session).updateRealm(rep, realm);
      return Response.noContent().build();
    } catch (ModelDuplicateException e) {
      return Flows.errors().exists("Realm " + rep.getRealm() + " already exists");
    }
  }
Esempio n. 16
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);
    }
  }
Esempio n. 17
0
 public UrlBean(
     RealmModel realm,
     Theme theme,
     URI baseURI,
     URI baseQueryURI,
     URI currentURI,
     String stateChecker) {
   this.realm = realm.getName();
   this.theme = theme;
   this.baseURI = baseURI;
   this.baseQueryURI = baseQueryURI;
   this.currentURI = currentURI;
   this.stateChecker = stateChecker;
 }
Esempio n. 18
0
  private static String verifyRedirectUri(
      UriInfo uriInfo,
      String rootUrl,
      String redirectUri,
      RealmModel realm,
      Set<String> validRedirects) {
    if (redirectUri == null) {
      logger.debug("No Redirect URI parameter specified");
      return null;
    } else if (validRedirects.isEmpty()) {
      logger.debug("No Redirect URIs supplied");
      redirectUri = null;
    } else {
      redirectUri = lowerCaseHostname(redirectUri);

      String r = redirectUri;
      Set<String> resolveValidRedirects = resolveValidRedirects(uriInfo, rootUrl, validRedirects);

      boolean valid = matchesRedirects(resolveValidRedirects, r);

      if (!valid
          && r.startsWith(Constants.INSTALLED_APP_URL)
          && r.indexOf(':', Constants.INSTALLED_APP_URL.length()) >= 0) {
        int i = r.indexOf(':', Constants.INSTALLED_APP_URL.length());

        StringBuilder sb = new StringBuilder();
        sb.append(r.substring(0, i));

        i = r.indexOf('/', i);
        if (i >= 0) {
          sb.append(r.substring(i));
        }

        r = sb.toString();

        valid = matchesRedirects(resolveValidRedirects, r);
      }
      if (valid && redirectUri.startsWith("/")) {
        redirectUri = relativeToAbsoluteURI(uriInfo, rootUrl, redirectUri);
      }
      redirectUri = valid ? redirectUri : null;
    }

    if (Constants.INSTALLED_APP_URN.equals(redirectUri)) {
      return Urls.realmInstalledAppUrnCallback(uriInfo.getBaseUri(), realm.getName()).toString();
    } else {
      return redirectUri;
    }
  }
Esempio n. 19
0
  @GET
  @NoCache
  @Produces("application/json")
  public RealmRepresentation getRealm() {
    if (auth.hasView()) {
      return ModelToRepresentation.toRepresentation(realm);
    } else {
      auth.requireAny();

      RealmRepresentation rep = new RealmRepresentation();
      rep.setRealm(realm.getName());

      return rep;
    }
  }
Esempio n. 20
0
  public InstallationAdapterConfig toInstallationRepresentation(
      RealmModel realmModel, OAuthClientModel model, URI baseUri) {
    InstallationAdapterConfig rep = new InstallationAdapterConfig();
    rep.setRealm(realmModel.getName());
    rep.setRealmKey(realmModel.getPublicKeyPem());
    rep.setSslNotRequired(realmModel.isSslNotRequired());
    rep.setAuthServerUrl(baseUri.toString());
    if (model.isPublicClient()) rep.setPublicClient(true);

    rep.setResource(model.getClientId());

    if (!model.isPublicClient()) {
      Map<String, String> creds = new HashMap<String, String>();
      creds.put(CredentialRepresentation.SECRET, model.getSecret());
      rep.setCredentials(creds);
    }

    return rep;
  }
Esempio n. 21
0
  public InstallationAdapterConfig toInstallationRepresentation(
      RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    InstallationAdapterConfig rep = new InstallationAdapterConfig();
    rep.setAuthServerUrl(baseUri.toString());
    rep.setRealm(realmModel.getName());
    rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase());

    if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true);
    if (clientModel.isBearerOnly()) rep.setBearerOnly(true);
    if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true);

    rep.setResource(clientModel.getClientId());

    if (showClientCredentialsAdapterConfig(clientModel)) {
      Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
      rep.setCredentials(adapterConfig);
    }

    return rep;
  }
Esempio n. 22
0
  /**
   * 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());
    try {
      RepresentationToModel.updateRealm(rep, realm);
      if (rep.isRealmCacheEnabled() != null && session.realms() instanceof CacheRealmProvider) {
        CacheRealmProvider cacheRealmProvider = (CacheRealmProvider) session.realms();
        cacheRealmProvider.setEnabled(rep.isRealmCacheEnabled());
      }
      if (rep.isUserCacheEnabled() != null && session.userStorage() instanceof CacheUserProvider) {
        CacheUserProvider cache = (CacheUserProvider) session.userStorage();
        cache.setEnabled(rep.isUserCacheEnabled());
      }

      // Refresh periodic sync tasks for configured federationProviders
      List<UserFederationProviderModel> federationProviders = realm.getUserFederationProviders();
      UsersSyncManager usersSyncManager = new UsersSyncManager();
      for (final UserFederationProviderModel fedProvider : federationProviders) {
        usersSyncManager.refreshPeriodicSyncForProvider(
            session.getKeycloakSessionFactory(),
            session.getProvider(TimerProvider.class),
            fedProvider,
            realm.getId());
      }

      adminEvent.operation(OperationType.UPDATE).representation(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) {
      throw e;
    } catch (Exception e) {
      logger.error(e);
      return ErrorResponse.error(
          "Failed to update " + rep.getRealm() + " Realm.", Response.Status.INTERNAL_SERVER_ERROR);
    }
  }
Esempio n. 23
0
  /**
   * Get the top-level representation of the realm
   *
   * <p>It will not include nested information like User and Client representations.
   *
   * @return
   */
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public RealmRepresentation getRealm() {
    if (auth.hasView()) {
      return ModelToRepresentation.toRepresentation(realm, false);
    } else {
      auth.requireAny();

      RealmRepresentation rep = new RealmRepresentation();
      rep.setRealm(realm.getName());

      if (auth.init(Resource.IDENTITY_PROVIDER).hasView()) {
        RealmRepresentation r = ModelToRepresentation.toRepresentation(realm, false);
        rep.setIdentityProviders(r.getIdentityProviders());
        rep.setIdentityProviderMappers(r.getIdentityProviderMappers());
      }

      return rep;
    }
  }
Esempio n. 24
0
 @Override
 public Response sendError(ClientSessionModel clientSession, Error error) {
   try {
     if ("true".equals(clientSession.getClient().getAttribute(SAML_IDP_INITIATED_LOGIN))) {
       if (error == Error.CANCELLED_BY_USER) {
         UriBuilder builder =
             RealmsResource.protocolUrl(uriInfo).path(SamlService.class, "idpInitiatedSSO");
         Map<String, String> params = new HashMap<>();
         params.put("realm", realm.getName());
         params.put("protocol", LOGIN_PROTOCOL);
         params.put(
             "client", clientSession.getClient().getAttribute(SAML_IDP_INITIATED_SSO_URL_NAME));
         URI redirect = builder.buildFromMap(params);
         return Response.status(302).location(redirect).build();
       } else {
         return ErrorPage.error(session, translateErrorToIdpInitiatedErrorMessage(error));
       }
     } else {
       SAML2ErrorResponseBuilder builder =
           new SAML2ErrorResponseBuilder()
               .destination(clientSession.getRedirectUri())
               .issuer(getResponseIssuer(realm))
               .status(translateErrorToSAMLStatus(error).get());
       try {
         JaxrsSAML2BindingBuilder binding =
             new JaxrsSAML2BindingBuilder()
                 .relayState(clientSession.getNote(GeneralConstants.RELAY_STATE));
         Document document = builder.buildDocument();
         return buildErrorResponse(clientSession, binding, document);
       } catch (Exception e) {
         return ErrorPage.error(session, Messages.FAILED_TO_PROCESS_RESPONSE);
       }
     }
   } finally {
     RestartLoginCookie.expireRestartCookie(realm, session.getContext().getConnection(), uriInfo);
     session.sessions().removeClientSession(realm, clientSession);
   }
 }
Esempio n. 25
0
  /**
   * Get the top-level representation of the realm
   *
   * <p>It will not include nested information like User and Client representations.
   *
   * @return
   */
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public RealmRepresentation getRealm() {
    if (auth.hasView()) {
      RealmRepresentation rep = ModelToRepresentation.toRepresentation(realm, false);
      if (session.realms() instanceof CacheRealmProvider) {
        CacheRealmProvider cacheRealmProvider = (CacheRealmProvider) session.realms();
        rep.setRealmCacheEnabled(cacheRealmProvider.isEnabled());
      }
      if (session.userStorage() instanceof CacheUserProvider) {
        CacheUserProvider cache = (CacheUserProvider) session.userStorage();
        rep.setUserCacheEnabled(cache.isEnabled());
      }
      return rep;
    } else {
      auth.requireAny();

      RealmRepresentation rep = new RealmRepresentation();
      rep.setRealm(realm.getName());
      return rep;
    }
  }
Esempio n. 26
0
 public UrlBean(RealmModel realm, Theme theme, URI baseURI, URI actionUri) {
   this.realm = realm.getName();
   this.theme = theme;
   this.baseURI = baseURI;
   this.actionuri = actionUri;
 }
Esempio n. 27
0
 protected String getResponseIssuer(RealmModel realm) {
   return RealmsResource.realmBaseUrl(uriInfo).build(realm.getName()).toString();
 }