Skip to content

Commit

Permalink
Allow to register OIDC tenants programmatically
Browse files Browse the repository at this point in the history
  • Loading branch information
michalvavrik committed Dec 28, 2024
1 parent 0d3fee5 commit 2bd44e1
Show file tree
Hide file tree
Showing 16 changed files with 1,069 additions and 668 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,37 @@ public class DiscoveryEndpointResponseFilter implements OidcResponseFilter {
<3> Use `OidcRequestContextProperties` request properties to get the tenant id.
<4> Get the response data as String.

== Programmatic OIDC start-up

OIDC tenants can be created programmatically like in the example below:

[source,java]
----
package io.quarkus.it.oidc;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;
public class OidcStartup {
void observe(@Observes Oidc oidc) {
oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/quarkus").build());
}
}
----

The code above is a programmatic equivalent to the following configuration in the `application.properties` file:

[source,properties]
----
quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
----

For more complex setup involving multiple tenants please see the xref:security-openid-connect-multitenancy.adoc#programmatic-startup[Programmatic OIDC start-up for multitenant application]
section of the OpenID Connect Multi-Tenancy guide.

== References

* xref:security-oidc-configuration-properties-reference.adoc[OIDC configuration properties]
Expand Down
41 changes: 41 additions & 0 deletions docs/src/main/asciidoc/security-oidc-code-flow-authentication.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -2049,6 +2049,47 @@ quarkus.log.category."io.quarkus.oidc.runtime.OidcRecorder".min-level=TRACE

From the `quarkus dev` console, type `j` to change the application global log level.

== Programmatic OIDC start-up

OIDC tenants can be created programmatically like in the example below:

[source,java]
----
package io.quarkus.it.oidc;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;
import static io.quarkus.oidc.runtime.OidcTenantConfig.ApplicationType.WEB_APP;
public class OidcStartup {
void observe(@Observes Oidc oidc) {
oidc.create(OidcTenantConfig
.authServerUrl("http://localhost:8180/realms/quarkus")
.applicationType(WEB_APP)
.clientId("quarkus-app")
.credentials().clientSecret("mysecret").end()
.build());
}
}
----

The code above is a programmatic equivalent to the following configuration in the `application.properties` file:

[source,properties]
----
quarkus.oidc.auth-server-url=http://localhost:8180/realms/quarkus
quarkus.oidc.application-type=web-app
quarkus.oidc.client-id=quarkus-app
quarkus.oidc.credentials.secret=mysecret
----

For more complex setup involving multiple tenants please see the xref:security-openid-connect-multitenancy.adoc#programmatic-startup[Programmatic OIDC start-up for multitenant application]
section of the OpenID Connect Multi-Tenancy guide.

== References

* xref:security-oidc-configuration-properties-reference.adoc[OIDC configuration properties]
Expand Down
69 changes: 69 additions & 0 deletions docs/src/main/asciidoc/security-openid-connect-multitenancy.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -1110,6 +1110,75 @@ The default tenant configuration is automatically disabled when `quarkus.oidc.au

Be aware that tenant-specific configurations can also be disabled, for example: `quarkus.oidc.tenant-a.tenant-enabled=false`.

[[programmatic-startup]]
== Programmatic OIDC start-up for multitenant application

Static OIDC tenants can be created programmatically like in the example below:

[source,java]
----
package io.quarkus.it.oidc;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;
public class OidcStartup {
void observe(@Observes Oidc oidc) { <1>
oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/tenant-one").tenantId("tenant-one").build());
oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/tenant-two").tenantId("tenant-two").build());
}
}
----
<1> Static tenants must be created in a synchronous manner from the observer method.

The code above is a programmatic equivalent to the following configuration in the `application.properties` file:

[source,properties]
----
quarkus.oidc.tenant-one.auth-server-url=http://localhost:8180/realms/tenant-one
quarkus.oidc.tenant-two.auth-server-url=http://localhost:8180/realms/tenant-two
----

You can also create static tenants based on the tenants configured in the `application.properties` file.
For example, if you need to add only tenant paths programmatically, you can:

.Static application.properties
[source,properties]
----
quarkus.oidc.tenant-two.auth-server-url=http://localhost:8180/realms/tenant-two
quarkus.oidc.tenant-two.tenant-paths=/api/tenant-two/*
----

.Additional property set programmatically
[source,java]
----
package io.quarkus.it.oidc;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import jakarta.enterprise.event.Observes;
public class OidcStartup {
void observe(@Observes Oidc oidc, OidcConfig config) {
oidc.create(OidcTenantConfig
.builder(config.namedTenants().get("tenant-two"))
.tenantPaths(getAdditionalTenantPath()) <1>
.build()
);
}
private String getAdditionalTenantPath() {
return "/additional-tenant-path";
}
}
----
<1> The tenant `tenant-two` will have two paths, `/additional-tenant-path` and `/api/tenant-two/*`.

== References

* xref:security-oidc-configuration-properties-reference.adoc[OIDC configuration properties]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
import java.util.function.Function;
import java.util.function.Supplier;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Singleton;

import org.keycloak.adapters.authorization.PolicyEnforcer;

Expand All @@ -19,14 +19,14 @@
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.common.runtime.OidcTlsSupport;
import io.quarkus.oidc.runtime.BlockingTaskRunner;
import io.quarkus.oidc.runtime.OidcConfig;
import io.quarkus.oidc.runtime.TenantConfigBean;
import io.quarkus.security.spi.runtime.BlockingSecurityExecutor;
import io.quarkus.tls.TlsConfigurationRegistry;
import io.quarkus.vertx.http.runtime.HttpConfiguration;
import io.smallrye.mutiny.Uni;
import io.vertx.ext.web.RoutingContext;

@Singleton
@ApplicationScoped
public class DefaultPolicyEnforcerResolver implements PolicyEnforcerResolver {

private final TenantPolicyConfigResolver dynamicConfigResolver;
Expand All @@ -36,7 +36,7 @@ public class DefaultPolicyEnforcerResolver implements PolicyEnforcerResolver {
private final long readTimeout;
private final OidcTlsSupport tlsSupport;

DefaultPolicyEnforcerResolver(OidcConfig oidcConfig, KeycloakPolicyEnforcerConfig config,
DefaultPolicyEnforcerResolver(TenantConfigBean tenantConfigBean, KeycloakPolicyEnforcerConfig config,
HttpConfiguration httpConfiguration, BlockingSecurityExecutor blockingSecurityExecutor,
Instance<TenantPolicyConfigResolver> configResolver,
InjectableInstance<TlsConfigurationRegistry> tlsConfigRegistryInstance) {
Expand All @@ -48,11 +48,11 @@ public class DefaultPolicyEnforcerResolver implements PolicyEnforcerResolver {
this.tlsSupport = OidcTlsSupport.empty();
}

var defaultTenantConfig = OidcConfig.getDefaultTenant(oidcConfig);
var defaultTenantConfig = tenantConfigBean.getDefaultTenant().oidcConfig();
var defaultTenantTlsSupport = tlsSupport.forConfig(defaultTenantConfig.tls());
this.defaultPolicyEnforcer = createPolicyEnforcer(defaultTenantConfig, config.defaultTenant(),
defaultTenantTlsSupport);
this.namedPolicyEnforcers = createNamedPolicyEnforcers(oidcConfig, config, tlsSupport);
this.namedPolicyEnforcers = createNamedPolicyEnforcers(tenantConfigBean, config, tlsSupport);
if (configResolver.isResolvable()) {
this.dynamicConfigResolver = configResolver.get();
this.requestContext = new BlockingTaskRunner<>(blockingSecurityExecutor);
Expand Down Expand Up @@ -105,15 +105,15 @@ public PolicyEnforcer apply(KeycloakPolicyEnforcerTenantConfig tenant) {
});
}

private static Map<String, PolicyEnforcer> createNamedPolicyEnforcers(OidcConfig oidcConfig,
private static Map<String, PolicyEnforcer> createNamedPolicyEnforcers(TenantConfigBean tenantConfigBean,
KeycloakPolicyEnforcerConfig config, OidcTlsSupport tlsSupport) {
if (config.namedTenants().isEmpty()) {
return Map.of();
}

Map<String, PolicyEnforcer> policyEnforcerTenants = new HashMap<>();
for (Map.Entry<String, KeycloakPolicyEnforcerTenantConfig> tenant : config.namedTenants().entrySet()) {
var oidcTenantConfig = getOidcTenantConfig(oidcConfig, tenant.getKey());
var oidcTenantConfig = getOidcTenantConfig(tenantConfigBean, tenant.getKey());
policyEnforcerTenants.put(tenant.getKey(),
createPolicyEnforcer(oidcTenantConfig, tenant.getValue(), tlsSupport.forConfig(oidcTenantConfig.tls())));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@
import io.quarkus.oidc.OIDCException;
import io.quarkus.oidc.common.runtime.OidcTlsSupport.TlsConfigSupport;
import io.quarkus.oidc.common.runtime.config.OidcCommonConfig;
import io.quarkus.oidc.runtime.OidcConfig;
import io.quarkus.oidc.runtime.OidcTenantConfig;
import io.quarkus.oidc.runtime.TenantConfigBean;
import io.quarkus.runtime.configuration.ConfigurationException;

public final class KeycloakPolicyEnforcerUtil {
Expand Down Expand Up @@ -224,15 +224,15 @@ private static boolean isNotComplexConfigKey(String key) {
return !key.contains(".");
}

static OidcTenantConfig getOidcTenantConfig(OidcConfig oidcConfig, String tenant) {
static OidcTenantConfig getOidcTenantConfig(TenantConfigBean tenantConfigBean, String tenant) {
if (tenant == null || DEFAULT_TENANT_ID.equals(tenant)) {
return OidcConfig.getDefaultTenant(oidcConfig);
return tenantConfigBean.getDefaultTenant().getOidcTenantConfig();
}

var oidcTenantConfig = oidcConfig.namedTenants().get(tenant);
if (oidcTenantConfig == null) {
var staticTenant = tenantConfigBean.getStaticTenant(tenant);
if (staticTenant == null || staticTenant.oidcConfig() == null) {
throw new ConfigurationException("Failed to find a matching OidcTenantConfig for tenant: " + tenant);
}
return oidcTenantConfig;
return staticTenant.oidcConfig();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import static io.quarkus.arc.processor.BuiltinScope.APPLICATION;
import static io.quarkus.arc.processor.DotNames.DEFAULT;
import static io.quarkus.arc.processor.DotNames.EVENT;
import static io.quarkus.arc.processor.DotNames.NAMED;
import static io.quarkus.oidc.common.runtime.OidcConstants.BEARER_SCHEME;
import static io.quarkus.oidc.common.runtime.OidcConstants.CODE_FLOW_CODE;
Expand All @@ -24,11 +25,14 @@
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.AnnotationValue;
import org.jboss.jandex.ClassType;
import org.jboss.jandex.DotName;
import org.jboss.jandex.ParameterizedType;
import org.jboss.jandex.Type;
import org.jboss.logging.Logger;

import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
import io.quarkus.arc.deployment.BeanContainerBuildItem;
import io.quarkus.arc.deployment.BeanDiscoveryFinishedBuildItem;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem;
import io.quarkus.arc.deployment.BeanRegistrationPhaseBuildItem.BeanConfiguratorBuildItem;
Expand All @@ -51,16 +55,18 @@
import io.quarkus.deployment.annotations.BuildSteps;
import io.quarkus.deployment.annotations.Consume;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Produce;
import io.quarkus.deployment.annotations.Record;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem;
import io.quarkus.deployment.builditem.RunTimeConfigBuilderBuildItem;
import io.quarkus.deployment.builditem.RunTimeConfigurationDefaultBuildItem;
import io.quarkus.deployment.builditem.RuntimeConfigSetupCompleteBuildItem;
import io.quarkus.deployment.builditem.SystemPropertyBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.oidc.AuthorizationCodeFlow;
import io.quarkus.oidc.BearerTokenAuthentication;
import io.quarkus.oidc.IdToken;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.Tenant;
import io.quarkus.oidc.TenantFeature;
import io.quarkus.oidc.TenantIdentityProvider;
Expand All @@ -87,6 +93,7 @@
import io.quarkus.tls.TlsRegistryBuildItem;
import io.quarkus.vertx.core.deployment.CoreVertxBuildItem;
import io.quarkus.vertx.http.deployment.EagerSecurityInterceptorBindingBuildItem;
import io.quarkus.vertx.http.deployment.FilterBuildItem;
import io.quarkus.vertx.http.deployment.HttpAuthMechanismAnnotationBuildItem;
import io.quarkus.vertx.http.deployment.SecurityInformationBuildItem;
import io.quarkus.vertx.http.runtime.HttpBuildTimeConfig;
Expand Down Expand Up @@ -167,8 +174,7 @@ AdditionalBeanBuildItem jwtClaimIntegration(Capabilities capabilities) {
}

@BuildStep
public void additionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans,
BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
public void additionalBeans(BuildProducer<AdditionalBeanBuildItem> additionalBeans) {
AdditionalBeanBuildItem.Builder builder = AdditionalBeanBuildItem.builder().setUnremovable();

builder.addBeanClass(OidcAuthenticationMechanism.class)
Expand Down Expand Up @@ -303,30 +309,40 @@ private static boolean isTenantIdentityProviderType(InjectionPointInfo ip) {
return TENANT_IDENTITY_PROVIDER_NAME.equals(ip.getRequiredType().name());
}

@Record(ExecutionTime.STATIC_INIT)
@BuildStep
void detectIfUserInfoRequired(OidcRecorder recorder, BeanRegistrationPhaseBuildItem beanRegistration) {
recorder.setUserInfoInjectionPointDetected(detectUserInfoRequired(beanRegistration));
}

// this ensures we initialize OIDC before HTTP router is finalized
// because we need TenantConfigBean in the BackChannelLogoutHandler
@Produce(FilterBuildItem.class)
@Consume(RuntimeConfigSetupCompleteBuildItem.class)
@Consume(BeanContainerBuildItem.class)
@Consume(SyntheticBeansRuntimeInitBuildItem.class)
@Record(ExecutionTime.RUNTIME_INIT)
@BuildStep
void initTenantConfigBean(OidcRecorder recorder) {
recorder.initTenantConfigBean();
}

@Record(ExecutionTime.RUNTIME_INIT)
@BuildStep
public SyntheticBeanBuildItem setup(
BeanRegistrationPhaseBuildItem beanRegistration,
SyntheticBeanBuildItem setup(
OidcConfig config,
OidcRecorder recorder,
CoreVertxBuildItem vertxBuildItem,
TlsRegistryBuildItem tlsRegistryBuildItem) {
return SyntheticBeanBuildItem.configure(TenantConfigBean.class).unremovable().types(TenantConfigBean.class)
.supplier(recorder.createTenantConfigBean(config, vertxBuildItem.getVertx(),
tlsRegistryBuildItem.registry(), detectUserInfoRequired(beanRegistration)))
.addInjectionPoint(ParameterizedType.create(EVENT, ClassType.create(Oidc.class)))
.createWith(recorder.createTenantConfigBean(config, vertxBuildItem.getVertx(), tlsRegistryBuildItem.registry()))
.destroyer(TenantConfigBean.Destroyer.class)
.scope(Singleton.class) // this should have been @ApplicationScoped but fails for some reason
.setRuntimeInit()
.done();
}

@Consume(SyntheticBeansRuntimeInitBuildItem.class)
@Record(ExecutionTime.RUNTIME_INIT)
@BuildStep
void initTenantConfigBean(OidcRecorder recorder) {
recorder.initTenantConfigBean();
}

@BuildStep
@Record(ExecutionTime.STATIC_INIT)
public void registerTenantResolverInterceptor(Capabilities capabilities, OidcRecorder recorder,
Expand Down
Loading

0 comments on commit 2bd44e1

Please sign in to comment.