Пример #1
0
  @Test
  public void testParsingSystemProps() throws IOException {
    System.setProperty("my.host", "foo");
    System.setProperty("con.pool.size", "200");
    System.setProperty("allow.any.hostname", "true");

    InputStream is = getClass().getClassLoader().getResourceAsStream("keycloak.json");

    AdapterConfig config = JsonSerialization.readValue(is, AdapterConfig.class, true);
    Assert.assertEquals("http://foo:8080/auth", config.getAuthServerUrl());
    Assert.assertEquals("external", config.getSslRequired());
    Assert.assertEquals("angular-product${non.existing}", config.getResource());
    Assert.assertTrue(config.isPublicClient());
    Assert.assertTrue(config.isAllowAnyHostname());
    Assert.assertEquals(100, config.getCorsMaxAge());
    Assert.assertEquals(200, config.getConnectionPoolSize());
  }
  protected KeycloakDeployment internalBuild(AdapterConfig adapterConfig) {
    if (adapterConfig.getRealm() == null) throw new RuntimeException("Must set 'realm' in config");
    deployment.setRealm(adapterConfig.getRealm());
    String resource = adapterConfig.getResource();
    if (resource == null) throw new RuntimeException("Must set 'resource' in config");
    deployment.setResourceName(resource);

    String realmKeyPem = adapterConfig.getRealmKey();
    if (realmKeyPem != null) {
      PublicKey realmKey;
      try {
        realmKey = PemUtils.decodePublicKey(realmKeyPem);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
      deployment.setRealmKey(realmKey);
    }
    if (adapterConfig.getSslRequired() != null) {
      deployment.setSslRequired(SslRequired.valueOf(adapterConfig.getSslRequired().toUpperCase()));
    } else {
      deployment.setSslRequired(SslRequired.EXTERNAL);
    }
    if (adapterConfig.getTokenStore() != null) {
      deployment.setTokenStore(TokenStore.valueOf(adapterConfig.getTokenStore().toUpperCase()));
    } else {
      deployment.setTokenStore(TokenStore.SESSION);
    }
    if (adapterConfig.getPrincipalAttribute() != null)
      deployment.setPrincipalAttribute(adapterConfig.getPrincipalAttribute());
    deployment.setResourceCredentials(adapterConfig.getCredentials());
    deployment.setPublicClient(adapterConfig.isPublicClient());
    deployment.setUseResourceRoleMappings(adapterConfig.isUseResourceRoleMappings());

    deployment.setExposeToken(adapterConfig.isExposeToken());

    if (adapterConfig.isCors()) {
      deployment.setCors(true);
      deployment.setCorsMaxAge(adapterConfig.getCorsMaxAge());
      deployment.setCorsAllowedHeaders(adapterConfig.getCorsAllowedHeaders());
      deployment.setCorsAllowedMethods(adapterConfig.getCorsAllowedMethods());
    }

    deployment.setBearerOnly(adapterConfig.isBearerOnly());
    deployment.setEnableBasicAuth(adapterConfig.isEnableBasicAuth());
    deployment.setAlwaysRefreshToken(adapterConfig.isAlwaysRefreshToken());
    deployment.setRegisterNodeAtStartup(adapterConfig.isRegisterNodeAtStartup());
    deployment.setRegisterNodePeriod(adapterConfig.getRegisterNodePeriod());

    if (realmKeyPem == null
        && adapterConfig.isBearerOnly()
        && adapterConfig.getAuthServerUrl() == null) {
      throw new IllegalArgumentException(
          "For bearer auth, you must set the realm-public-key or auth-server-url");
    }
    if (realmKeyPem == null
        || !deployment.isBearerOnly()
        || deployment.isRegisterNodeAtStartup()
        || deployment.getRegisterNodePeriod() != -1) {
      deployment.setClient(new HttpClientBuilder().build(adapterConfig));
    }
    if (adapterConfig.getAuthServerUrl() == null
        && (!deployment.isBearerOnly() || realmKeyPem == null)) {
      throw new RuntimeException("You must specify auth-url");
    }
    deployment.setAuthServerBaseUrl(adapterConfig);

    log.debug(
        "Use authServerUrl: "
            + deployment.getAuthServerBaseUrl()
            + ", tokenUrl: "
            + deployment.getTokenUrl()
            + ", relativeUrls: "
            + deployment.getRelativeUrls());
    return deployment;
  }
Пример #3
0
  @Override
  public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {
    if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK")) {
      log.info("auth-method is not keycloak!");
      return;
    }
    log.info("KeycloakServletException initialization");
    InputStream is = servletContext.getResourceAsStream("/WEB-INF/keycloak.json");
    if (is == null)
      throw new RuntimeException("Unable to find /WEB-INF/keycloak.json configuration file");
    RealmConfigurationLoader loader = new RealmConfigurationLoader(is);
    loader.init(true);
    AdapterConfig keycloakConfig = loader.getAdapterConfig();
    RealmConfiguration realmConfiguration = loader.getRealmConfiguration();
    PreflightCorsHandler.Wrapper preflight = new PreflightCorsHandler.Wrapper(keycloakConfig);
    UserSessionManagement userSessionManagement = new UserSessionManagement(realmConfiguration);
    ServletKeycloakAuthenticationMechanism auth = null;
    if (keycloakConfig.isBearerOnly()) {
      auth =
          new ServletKeycloakAuthenticationMechanism(
              keycloakConfig,
              loader.getResourceMetadata(),
              deploymentInfo.getConfidentialPortManager());
    } else {
      auth =
          new ServletKeycloakAuthenticationMechanism(
              userSessionManagement,
              keycloakConfig,
              realmConfiguration,
              deploymentInfo.getConfidentialPortManager());
    }
    ServletAuthenticatedActionsHandler.Wrapper actions =
        new ServletAuthenticatedActionsHandler.Wrapper(keycloakConfig);

    // setup handlers

    deploymentInfo.addInitialHandlerChainWrapper(preflight); // cors preflight
    deploymentInfo.addOuterHandlerChainWrapper(
        new ServletAdminActionsHandler.Wrapper(realmConfiguration, userSessionManagement));
    final ServletKeycloakAuthenticationMechanism theAuth = auth;
    deploymentInfo.addAuthenticationMechanism(
        "KEYCLOAK",
        new AuthenticationMechanismFactory() {
          @Override
          public AuthenticationMechanism create(
              String s, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
            return theAuth;
          }
        }); // authentication
    deploymentInfo.addInnerHandlerChainWrapper(
        ServletPropagateSessionHandler.WRAPPER); // propagates SkeletonKeySession
    deploymentInfo.addInnerHandlerChainWrapper(actions); // handles authenticated actions and cors.

    deploymentInfo.setIdentityManager(
        new IdentityManager() {
          @Override
          public Account verify(Account account) {
            log.info("Verifying account in IdentityManager");
            return account;
          }

          @Override
          public Account verify(String id, Credential credential) {
            log.warn("Shouldn't call verify!!!");
            throw new IllegalStateException("Not allowed");
          }

          @Override
          public Account verify(Credential credential) {
            log.warn("Shouldn't call verify!!!");
            throw new IllegalStateException("Not allowed");
          }
        });

    log.info("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
    ServletSessionConfig cookieConfig = new ServletSessionConfig();
    cookieConfig.setPath(deploymentInfo.getContextPath());
    deploymentInfo.setServletSessionConfig(cookieConfig);
  }