Skip to content

Commit

Permalink
Merge pull request #45294 from michalvavrik/feature/programmatic-oidc…
Browse files Browse the repository at this point in the history
…-startup

Allow to create static OIDC tenants programmatically
  • Loading branch information
sberyozkin authored Jan 1, 2025
2 parents 3b22087 + e85bc86 commit 15ffade
Show file tree
Hide file tree
Showing 16 changed files with 1,078 additions and 671 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,58 @@ 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 jakarta.enterprise.event.Observes;
public class OidcStartup {
void observe(@Observes Oidc oidc) {
oidc.createServiceApp("http://localhost:8180/realms/quarkus");
}
}
----

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
----

Should you need to configure more OIDC tenant properties, use the `OidcTenantConfig` builder 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 createDefaultTenant(@Observes Oidc oidc) {
var defaultTenant = OidcTenantConfig
.authServerUrl("http://localhost:8180/realms/quarkus")
.token().requireJwtIntrospectionOnly().end()
.build();
oidc.create(defaultTenant);
}
}
----

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
57 changes: 57 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,63 @@ 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 jakarta.enterprise.event.Observes;
public class OidcStartup {
void observe(@Observes Oidc oidc) {
oidc.createWebApp("http://localhost:8180/realms/quarkus", "quarkus-app", "mysecret");
}
}
----

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
----

Should you need to configure more OIDC tenant properties, use the `OidcTenantConfig` builder like in the example below:

[source,java]
----
package io.quarkus.it.oidc;
import io.quarkus.oidc.Oidc;
import io.quarkus.oidc.OidcTenantConfig;
import io.quarkus.oidc.common.runtime.config.OidcClientCommonConfig.Credentials.Secret.Method;
import jakarta.enterprise.event.Observes;
public class OidcStartup {
void createDefaultTenant(@Observes Oidc oidc) {
var defaultTenant = OidcTenantConfig
.authServerUrl("http://localhost:8180/realms/quarkus/")
.clientId("quarkus-app")
.credentials().clientSecret("mysecret", Method.POST).end()
.build();
oidc.create(defaultTenant);
}
}
----

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
34 changes: 34 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,40 @@ 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 multiple tenants

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()); <2>
oidc.create(OidcTenantConfig.authServerUrl("http://localhost:8180/realms/tenant-two").tenantId("tenant-two").build()); <3>
}
}
----
<1> Observe OIDC event.
<2> Create OIDC tenant 'tenant-one'.
<3> Create OIDC tenant 'tenant-two'.

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
----

== 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 @@ -84,9 +90,11 @@
import io.quarkus.oidc.runtime.OidcUtils;
import io.quarkus.oidc.runtime.TenantConfigBean;
import io.quarkus.oidc.runtime.providers.AzureAccessTokenCustomizer;
import io.quarkus.security.runtime.SecurityConfig;
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 +175,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 +310,38 @@ private static boolean isTenantIdentityProviderType(InjectionPointInfo ip) {
return TENANT_IDENTITY_PROVIDER_NAME.equals(ip.getRequiredType().name());
}

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

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

0 comments on commit 15ffade

Please sign in to comment.