Service Injection via Quarkus

We are implementing our own custom authenticator, and we need to inject services that we developed for the custom authentication. We have identified three solutions to achieve this:

  • Keycloak provider
  • Injection via Quarkus
  • Implementation via Java interfaces

The solution we want to implement is through Quarkus; however, we are facing integration difficulties (such as conflicts).

Is there an example of service injection inside a custom authenticator (specifically an implementation example)?

When you say “injection” you mean CDI?
CDI is not possible in Keycloak, it’s also mentioned in the docs that this is disabled.

1 Like

I’m a bit limited in what I can share from my employer but I can outline the basic setup for writing a customer authenticator in Java.

The short answer is, do all three!

You’ll want to write an AuthenticatorFactory, something like


@AutoService(AuthenticatorFactory.class)
public class SomethingAuthenticatorFactory implements AuthenticatorFactory, ServerInfoAwareProviderFactory {

@Override
public String getId() {
  return "something-customer-authenticator";
}
...
}

The AutoService annotation is from a plugin com.google.auto.service.AutoService which will automatically add the class to the META-INF folder which is needed for SPI.

When you package that into a jar and drop it into the providers directory and start up Keycloak you should see your id value in the realm configuration under “Provider Info” tab.

Your AuthenticatorFactory must return your custom authenticator, and that’s where your custom code is going to be. Your authenticator will be constructed from the factory each time it is needed. The ID value you use will be available in the Authentication configuration when you setup a new or existing authentication flow.

Quarkus has a nice feature where you can trigger a class instantiation at startup – see the code below;


import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Singleton;
...

@Startup
@Singleton
public class MyStartupListener {

  @PostConstruct
  public void doStartupStuff() {
     // load configs, database connection setup, whatever else here

  }

}

If you want to setup things like JNDI or static singletons for services, datasources, etc this is a great place to do that so you can keep your authenticator code clean.

Here’s the Keycloak documenation for writing SPIs Server Developer Guide

and the docs specific for an authenticator
https://www.keycloak.org/docs/latest/server_development/index.html#_auth_spi

I hope this helps, if you’re running into a specific issue please send us your error message and I can try to help troubleshoot.

1 Like