コード例 #1
0
ファイル: UserAdapter.java プロジェクト: hh201020/keycloak
  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;
  }
コード例 #2
0
ファイル: SamlProtocol.java プロジェクト: gautric/keycloak
  protected boolean isLogoutPostBindingForClient(ClientSessionModel clientSession) {
    ClientModel client = clientSession.getClient();
    SamlClient samlClient = new SamlClient(client);
    String logoutPostUrl = client.getAttribute(SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE);
    String logoutRedirectUrl =
        client.getAttribute(SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE);

    if (logoutPostUrl == null) {
      // if we don't have a redirect uri either, return true and default to the admin url + POST
      // binding
      if (logoutRedirectUrl == null) return true;
      return false;
    }

    if (samlClient.forcePostBinding()) {
      return true; // configured to force a post binding and post binding logout url is not null
    }

    String bindingType = clientSession.getNote(SAML_BINDING);

    // if the login binding was POST, return true
    if (SAML_POST_BINDING.equals(bindingType)) return true;

    if (logoutRedirectUrl == null)
      return true; // we don't have a redirect binding url, so use post binding

    return false; // redirect binding
  }
コード例 #3
0
ファイル: ClientResource.java プロジェクト: stianst/keycloak
  /**
   * Get offline sessions for client
   *
   * <p>Returns a list of offline user sessions associated with this client
   *
   * @param firstResult Paging offset
   * @param maxResults Maximum results size (defaults to 100)
   * @return
   */
  @Path("offline-sessions")
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public List<UserSessionRepresentation> getOfflineUserSessions(
      @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) {
    auth.requireView();

    if (client == null) {
      throw new NotFoundException("Could not find client");
    }

    firstResult = firstResult != null ? firstResult : -1;
    maxResults = maxResults != null ? maxResults : Constants.DEFAULT_MAX_RESULTS;
    List<UserSessionRepresentation> sessions = new ArrayList<UserSessionRepresentation>();
    List<UserSessionModel> userSessions =
        session
            .sessions()
            .getOfflineUserSessions(client.getRealm(), client, firstResult, maxResults);
    for (UserSessionModel userSession : userSessions) {
      UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(userSession);

      // Update lastSessionRefresh with the timestamp from clientSession
      for (ClientSessionModel clientSession : userSession.getClientSessions()) {
        if (client.getId().equals(clientSession.getClient().getId())) {
          rep.setLastAccess(Time.toMillis(clientSession.getTimestamp()));
          break;
        }
      }

      sessions.add(rep);
    }
    return sessions;
  }
コード例 #4
0
ファイル: TokenManager.java プロジェクト: majinding/keycloak
 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;
 }
コード例 #5
0
    private ClientSessionCode parseClientSessionCode(String code) {
      ClientSessionCode clientCode = ClientSessionCode.parse(code, this.session, this.realm);

      if (clientCode != null
          && clientCode.isValid(AUTHENTICATE.name(), ClientSessionCode.ActionType.LOGIN)) {
        ClientSessionModel clientSession = clientCode.getClientSession();

        if (clientSession != null) {
          ClientModel client = clientSession.getClient();

          if (client == null) {
            throw new IdentityBrokerException("Invalid client");
          }

          logger.debugf("Got authorization code from client [%s].", client.getClientId());
        }

        logger.debugf("Authorization code is valid.");

        return clientCode;
      }

      throw new IdentityBrokerException(
          "Invalid code, please login again through your application.");
    }
コード例 #6
0
ファイル: TokenManager.java プロジェクト: majinding/keycloak
  protected void addComposites(AccessToken token, RoleModel role) {
    AccessToken.Access access = null;
    if (role.getContainer() instanceof RealmModel) {
      access = token.getRealmAccess();
      if (token.getRealmAccess() == null) {
        access = new AccessToken.Access();
        token.setRealmAccess(access);
      } else if (token.getRealmAccess().getRoles() != null
          && token.getRealmAccess().isUserInRole(role.getName())) return;

    } else {
      ClientModel app = (ClientModel) role.getContainer();
      access = token.getResourceAccess(app.getClientId());
      if (access == null) {
        access = token.addAccess(app.getClientId());
        if (app.isSurrogateAuthRequired()) access.verifyCaller(true);
      } else if (access.isUserInRole(role.getName())) return;
    }
    access.addRole(role.getName());
    if (!role.isComposite()) return;

    for (RoleModel composite : role.getComposites()) {
      addComposites(token, composite);
    }
  }
コード例 #7
0
ファイル: AccountService.java プロジェクト: rishiHPE/keycloak
  private String[] getReferrer() {
    String referrer = uriInfo.getQueryParameters().getFirst("referrer");
    if (referrer == null) {
      return null;
    }

    String referrerUri = uriInfo.getQueryParameters().getFirst("referrer_uri");

    ClientModel referrerClient = realm.getClientByClientId(referrer);
    if (referrerClient != null) {
      if (referrerUri != null) {
        referrerUri = RedirectUtils.verifyRedirectUri(uriInfo, referrerUri, realm, referrerClient);
      } else {
        referrerUri =
            ResolveRelative.resolveRelativeUri(
                uriInfo.getRequestUri(), client.getRootUrl(), referrerClient.getBaseUrl());
      }

      if (referrerUri != null) {
        return new String[] {referrer, referrerUri};
      }
    } else if (referrerUri != null) {
      referrerClient = realm.getClientByClientId(referrer);
      if (client != null) {
        referrerUri = RedirectUtils.verifyRedirectUri(uriInfo, referrerUri, realm, referrerClient);

        if (referrerUri != null) {
          return new String[] {referrer, referrerUri};
        }
      }
    }

    return null;
  }
コード例 #8
0
  /**
   * Revoke consent and offline tokens for particular client from user
   *
   * @param id User id
   * @param clientId Client id
   */
  @Path("{id}/consents/{client}")
  @DELETE
  @NoCache
  public void revokeConsent(
      final @PathParam("id") String id, final @PathParam("client") String clientId) {
    auth.requireManage();
    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      throw new NotFoundException("User not found");
    }

    ClientModel client = realm.getClientByClientId(clientId);
    boolean revokedConsent = user.revokeConsentForClient(client.getId());
    boolean revokedOfflineToken = new UserSessionManager(session).revokeOfflineToken(user, client);

    if (revokedConsent) {
      // Logout clientSessions for this user and client
      AuthenticationManager.backchannelUserFromClient(
          session, realm, user, client, uriInfo, headers);
    }

    if (!revokedConsent && !revokedOfflineToken) {
      throw new NotFoundException("Consent nor offline token not found");
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success();
  }
コード例 #9
0
ファイル: ClientManager.java プロジェクト: gautric/keycloak
  public Set<String> validateRegisteredNodes(ClientModel client) {
    Map<String, Integer> registeredNodes = client.getRegisteredNodes();
    if (registeredNodes == null || registeredNodes.isEmpty()) {
      return Collections.emptySet();
    }

    int currentTime = Time.currentTime();

    Set<String> validatedNodes = new TreeSet<String>();
    if (client.getNodeReRegistrationTimeout() > 0) {
      List<String> toRemove = new LinkedList<String>();
      for (Map.Entry<String, Integer> entry : registeredNodes.entrySet()) {
        Integer lastReRegistration = entry.getValue();
        if (lastReRegistration + client.getNodeReRegistrationTimeout() < currentTime) {
          toRemove.add(entry.getKey());
        } else {
          validatedNodes.add(entry.getKey());
        }
      }

      // Remove time-outed nodes
      for (String node : toRemove) {
        client.unregisterNode(node);
      }
    } else {
      // Periodic node reRegistration is disabled, so allow all nodes
      validatedNodes.addAll(registeredNodes.keySet());
    }

    return validatedNodes;
  }
コード例 #10
0
ファイル: RedirectUtils.java プロジェクト: pdrozd/keycloak
 public static String verifyRedirectUri(
     UriInfo uriInfo, String redirectUri, RealmModel realm, ClientModel client) {
   if (client != null)
     return verifyRedirectUri(
         uriInfo, client.getRootUrl(), redirectUri, realm, client.getRedirectUris());
   return null;
 }
コード例 #11
0
ファイル: SamlProtocol.java プロジェクト: gautric/keycloak
  @Override
  public void backchannelLogout(UserSessionModel userSession, ClientSessionModel clientSession) {
    ClientModel client = clientSession.getClient();
    SamlClient samlClient = new SamlClient(client);
    String logoutUrl = getLogoutServiceUrl(uriInfo, client, SAML_POST_BINDING);
    if (logoutUrl == null) {
      logger.warnv(
          "Can't do backchannel logout. No SingleLogoutService POST Binding registered for client: {1}",
          client.getClientId());
      return;
    }
    SAML2LogoutRequestBuilder logoutBuilder = createLogoutRequest(logoutUrl, clientSession, client);

    String logoutRequestString = null;
    try {
      JaxrsSAML2BindingBuilder binding = createBindingBuilder(samlClient);
      logoutRequestString = binding.postBinding(logoutBuilder.buildDocument()).encoded();
    } catch (Exception e) {
      logger.warn("failed to send saml logout", e);
      return;
    }

    HttpClient httpClient = session.getProvider(HttpClientProvider.class).getHttpClient();
    for (int i = 0; i < 2; i++) { // follow redirects once
      try {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(
            new BasicNameValuePair(GeneralConstants.SAML_REQUEST_KEY, logoutRequestString));
        formparams.add(
            new BasicNameValuePair("BACK_CHANNEL_LOGOUT", "BACK_CHANNEL_LOGOUT")); // for Picketlink
        // todo remove
        // this
        UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8");
        HttpPost post = new HttpPost(logoutUrl);
        post.setEntity(form);
        HttpResponse response = httpClient.execute(post);
        try {
          int status = response.getStatusLine().getStatusCode();
          if (status == 302 && !logoutUrl.endsWith("/")) {
            String redirect = response.getFirstHeader(HttpHeaders.LOCATION).getValue();
            String withSlash = logoutUrl + "/";
            if (withSlash.equals(redirect)) {
              logoutUrl = withSlash;
              continue;
            }
          }
        } finally {
          HttpEntity entity = response.getEntity();
          if (entity != null) {
            InputStream is = entity.getContent();
            if (is != null) is.close();
          }
        }
      } catch (IOException e) {
        logger.warn("failed to send saml logout", e);
      }
      break;
    }
  }
コード例 #12
0
ファイル: RedirectUtils.java プロジェクト: pdrozd/keycloak
 private static Set<String> getValidateRedirectUris(UriInfo uriInfo, RealmModel realm) {
   Set<String> redirects = new HashSet<>();
   for (ClientModel client : realm.getClients()) {
     redirects.addAll(
         resolveValidRedirects(uriInfo, client.getRootUrl(), client.getRedirectUris()));
   }
   return redirects;
 }
コード例 #13
0
ファイル: ClientAdapter.java プロジェクト: tfzhang/keycloak
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || !(o instanceof ClientModel)) return false;

    ClientModel that = (ClientModel) o;
    return that.getId().equals(getId());
  }
コード例 #14
0
  public ApplicationsBean(KeycloakSession session, RealmModel realm, UserModel user) {

    Set<ClientModel> offlineClients =
        new UserSessionManager(session).findClientsWithOfflineToken(realm, user);

    List<ClientModel> realmClients = realm.getClients();
    for (ClientModel client : realmClients) {
      // Don't show bearerOnly clients
      if (client.isBearerOnly()) {
        continue;
      }

      Set<RoleModel> availableRoles = TokenManager.getAccess(null, false, client, user);
      // Don't show applications, which user doesn't have access into (any available roles)
      if (availableRoles.isEmpty()) {
        continue;
      }
      List<RoleModel> realmRolesAvailable = new LinkedList<RoleModel>();
      MultivaluedHashMap<String, ClientRoleEntry> resourceRolesAvailable =
          new MultivaluedHashMap<String, ClientRoleEntry>();
      processRoles(availableRoles, realmRolesAvailable, resourceRolesAvailable);

      List<RoleModel> realmRolesGranted = new LinkedList<RoleModel>();
      MultivaluedHashMap<String, ClientRoleEntry> resourceRolesGranted =
          new MultivaluedHashMap<String, ClientRoleEntry>();
      List<String> claimsGranted = new LinkedList<String>();
      if (client.isConsentRequired()) {
        UserConsentModel consent = user.getConsentByClient(client.getId());

        if (consent != null) {
          processRoles(consent.getGrantedRoles(), realmRolesGranted, resourceRolesGranted);

          for (ProtocolMapperModel protocolMapper : consent.getGrantedProtocolMappers()) {
            claimsGranted.add(protocolMapper.getConsentText());
          }
        }
      }

      List<String> additionalGrants = new ArrayList<>();
      if (offlineClients.contains(client)) {
        additionalGrants.add("${offlineToken}");
      }

      ApplicationEntry appEntry =
          new ApplicationEntry(
              realmRolesAvailable,
              resourceRolesAvailable,
              realmRolesGranted,
              resourceRolesGranted,
              client,
              claimsGranted,
              additionalGrants);
      applications.add(appEntry);
    }
  }
コード例 #15
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;
  }
コード例 #16
0
  /**
   * Get consents granted by the user
   *
   * @param id User id
   * @return
   */
  @Path("{id}/consents")
  @GET
  @NoCache
  @Produces(MediaType.APPLICATION_JSON)
  public List<Map<String, Object>> getConsents(final @PathParam("id") String id) {
    auth.requireView();
    UserModel user = session.users().getUserById(id, realm);
    if (user == null) {
      throw new NotFoundException("User not found");
    }

    List<Map<String, Object>> result = new LinkedList<>();

    Set<ClientModel> offlineClients =
        new UserSessionManager(session).findClientsWithOfflineToken(realm, user);

    for (ClientModel client : realm.getClients()) {
      UserConsentModel consent = user.getConsentByClient(client.getId());
      boolean hasOfflineToken = offlineClients.contains(client);

      if (consent == null && !hasOfflineToken) {
        continue;
      }

      UserConsentRepresentation rep =
          (consent == null) ? null : ModelToRepresentation.toRepresentation(consent);

      Map<String, Object> currentRep = new HashMap<>();
      currentRep.put("clientId", client.getClientId());
      currentRep.put(
          "grantedProtocolMappers",
          (rep == null ? Collections.emptyMap() : rep.getGrantedProtocolMappers()));
      currentRep.put(
          "grantedRealmRoles",
          (rep == null ? Collections.emptyList() : rep.getGrantedRealmRoles()));
      currentRep.put(
          "grantedClientRoles",
          (rep == null ? Collections.emptyMap() : rep.getGrantedClientRoles()));

      List<Map<String, String>> additionalGrants = new LinkedList<>();
      if (hasOfflineToken) {
        Map<String, String> offlineTokens = new HashMap<>();
        offlineTokens.put("client", client.getId());
        // TODO: translate
        offlineTokens.put("key", "Offline Token");
        additionalGrants.add(offlineTokens);
      }
      currentRep.put("additionalGrants", additionalGrants);

      result.add(currentRep);
    }

    return result;
  }
コード例 #17
0
ファイル: ClientManager.java プロジェクト: gautric/keycloak
  private boolean showClientCredentialsAdapterConfig(ClientModel client) {
    if (client.isPublicClient()) {
      return false;
    }

    if (client.isBearerOnly() && client.getNodeReRegistrationTimeout() <= 0) {
      return false;
    }

    return true;
  }
コード例 #18
0
  private void grantPermissionsToRealmCreator(RealmModel realm) {
    if (auth.hasRealmRole(AdminRoles.ADMIN)) {
      return;
    }

    RealmModel adminRealm = new RealmManager(session).getKeycloakAdminstrationRealm();
    ClientModel realmAdminApp = realm.getMasterAdminClient();
    for (String r : AdminRoles.ALL_REALM_ROLES) {
      RoleModel role = realmAdminApp.getRole(r);
      auth.getUser().grantRole(role);
    }
  }
コード例 #19
0
ファイル: ClientManager.java プロジェクト: gautric/keycloak
  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();
  }
コード例 #20
0
  @Test
  public void testGetById() {
    Assert.assertEquals(realm1, model.getRealm("id1"));
    Assert.assertEquals(realm1, model.getRealmByName("realm1"));
    Assert.assertEquals(realm2, model.getRealm("id2"));
    Assert.assertEquals(realm2, model.getRealmByName("realm2"));

    ClientModel r1app1 = realm1.getClientByClientId("app1");
    ClientModel r1app2 = realm1.getClientByClientId("app2");
    ClientModel r2app1 = realm2.getClientByClientId("app1");
    ClientModel r2app2 = realm2.getClientByClientId("app2");

    Assert.assertEquals(r1app1, realm1.getClientById(r1app1.getId()));
    Assert.assertNull(realm2.getClientById(r1app1.getId()));

    ClientModel r2cl1 = realm2.getClientByClientId("cl1");
    Assert.assertEquals(r2cl1.getId(), realm2.getClientById(r2cl1.getId()).getId());
    Assert.assertNull(realm1.getClientByClientId(r2cl1.getId()));

    RoleModel r1App1Role = r1app1.getRole("app1Role1");
    Assert.assertEquals(r1App1Role, realm1.getRoleById(r1App1Role.getId()));
    Assert.assertNull(realm2.getRoleById(r1App1Role.getId()));

    RoleModel r2Role1 = realm2.getRole("role2");
    Assert.assertNull(realm1.getRoleById(r2Role1.getId()));
    Assert.assertEquals(r2Role1, realm2.getRoleById(r2Role1.getId()));
  }
コード例 #21
0
ファイル: SamlProtocol.java プロジェクト: gautric/keycloak
 public static String getLogoutServiceUrl(
     UriInfo uriInfo, ClientModel client, String bindingType) {
   String logoutServiceUrl = null;
   if (SAML_POST_BINDING.equals(bindingType)) {
     logoutServiceUrl = client.getAttribute(SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE);
   } else {
     logoutServiceUrl = client.getAttribute(SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE);
   }
   if (logoutServiceUrl == null && client instanceof ClientModel)
     logoutServiceUrl = ((ClientModel) client).getManagementUrl();
   if (logoutServiceUrl == null || logoutServiceUrl.trim().equals("")) return null;
   return ResourceAdminManager.resolveUri(
       uriInfo.getRequestUri(), client.getRootUrl(), logoutServiceUrl);
 }
コード例 #22
0
  private void createObjects(RealmModel realm) {
    ClientModel app1 = realm.addClient("app1");
    realm.addClient("app2");

    realmManager.getSession().users().addUser(realm, "user1");
    realmManager.getSession().users().addUser(realm, "user2");

    realm.addRole("role1");
    realm.addRole("role2");

    app1.addRole("app1Role1");
    app1.addScopeMapping(realm.getRole("role1"));

    realm.addClient("cl1");
  }
コード例 #23
0
  @Override
  public void postInit(KeycloakSessionFactory factory) {
    factory.register(
        event -> {
          if (event instanceof ClientRemovedEvent) {
            KeycloakSession keycloakSession = ((ClientRemovedEvent) event).getKeycloakSession();
            AuthorizationProvider provider =
                keycloakSession.getProvider(AuthorizationProvider.class);
            PolicyStore policyStore = provider.getStoreFactory().getPolicyStore();
            ClientModel removedClient = ((ClientRemovedEvent) event).getClient();

            policyStore
                .findByType(getId())
                .forEach(
                    policy -> {
                      List<String> clients = new ArrayList<>();

                      for (String clientId : getClients(policy)) {
                        if (!clientId.equals(removedClient.getId())) {
                          clients.add(clientId);
                        }
                      }

                      try {
                        if (clients.isEmpty()) {
                          policyStore
                              .findDependentPolicies(policy.getId())
                              .forEach(
                                  dependentPolicy -> {
                                    dependentPolicy.removeAssociatedPolicy(policy);
                                  });
                          policyStore.delete(policy.getId());
                        } else {
                          policy
                              .getConfig()
                              .put("clients", JsonSerialization.writeValueAsString(clients));
                        }
                      } catch (IOException e) {
                        throw new RuntimeException(
                            "Error while synchronizing clients with policy ["
                                + policy.getName()
                                + "].",
                            e);
                      }
                    });
          }
        });
  }
コード例 #24
0
            @Override
            public void config(
                RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
              ClientModel app = appRealm.addClient("resource-owner");
              app.setSecret("secret");

              UserModel user = session.users().addUser(appRealm, "direct-login");
              user.setEmail("direct-login@localhost");
              user.setEnabled(true);

              userId = user.getId();

              session
                  .users()
                  .updateCredential(appRealm, user, UserCredentialModel.password("password"));
            }
コード例 #25
0
ファイル: UserAdapter.java プロジェクト: hh201020/keycloak
  @Override
  public Set<RoleModel> getClientRoleMappings(ClientModel app) {
    Set<RoleModel> roleMappings = getRoleMappings();

    Set<RoleModel> roles = new HashSet<RoleModel>();
    for (RoleModel role : roleMappings) {
      RoleContainerModel container = role.getContainer();
      if (container instanceof ClientModel) {
        ClientModel appModel = (ClientModel) container;
        if (appModel.getId().equals(app.getId())) {
          roles.add(role);
        }
      }
    }
    return roles;
  }
コード例 #26
0
ファイル: ClientAdapter.java プロジェクト: tfzhang/keycloak
 @Override
 public RoleModel addRole(String id, String name) {
   getDelegateForUpdate();
   RoleModel role = updated.addRole(id, name);
   cacheSession.registerRoleInvalidation(role.getId());
   return role;
 }
コード例 #27
0
ファイル: ClientAdapter.java プロジェクト: tfzhang/keycloak
 @Override
 public RoleModel getRole(String name) {
   if (updated != null) return updated.getRole(name);
   String id = cached.getRoles().get(name);
   if (id == null) return null;
   return cacheSession.getRoleById(id, cachedRealm);
 }
コード例 #28
0
ファイル: ClientAdapter.java プロジェクト: tfzhang/keycloak
 @Override
 public Map<String, String> getAttributes() {
   if (updated != null) return updated.getAttributes();
   Map<String, String> copy = new HashMap<String, String>();
   copy.putAll(cached.getAttributes());
   return copy;
 }
コード例 #29
0
ファイル: ClientAdapter.java プロジェクト: tfzhang/keycloak
 public Set<RoleModel> getScopeMappings() {
   if (updated != null) return updated.getScopeMappings();
   Set<RoleModel> roles = new HashSet<RoleModel>();
   for (String id : cached.getScope()) {
     roles.add(cacheSession.getRoleById(id, getRealm()));
   }
   return roles;
 }
コード例 #30
0
 /**
  * Get client session stats
  *
  * <p>Returns a JSON map. The key is the client id, the value is the number of sessions that
  * currently are active with that client. Only clients that actually have a session associated
  * with them will be in this map.
  *
  * @return
  */
 @Path("client-session-stats")
 @GET
 @NoCache
 @Produces(MediaType.APPLICATION_JSON)
 public List<Map<String, String>> getClientSessionStats() {
   auth.requireView();
   List<Map<String, String>> data = new LinkedList<Map<String, String>>();
   for (ClientModel client : realm.getClients()) {
     int size = session.sessions().getActiveUserSessions(client.getRealm(), client);
     if (size == 0) continue;
     Map<String, String> map = new HashMap<String, String>();
     map.put("id", client.getId());
     map.put("clientId", client.getClientId());
     map.put("active", size + "");
     data.add(map);
   }
   return data;
 }