Retrieving Environment Variable in custom SPI

How can I define and retrieve a environment variable for use in a custom SPI? For example an API Key that will be defined in the Keycloak environment (Docker environment variable).

I have read the documentation here for Provider Configuration Option Format but everything I try for this does not work.

In my example I am implementing this Have I Been PWNED SPI but adding an API Key.

I have tried defining the docker env variable as KC_SPI_PASSWORD_POLICY_HIBP_PASSWORD_POLICY_APIKEY:

environment:
  - KC_SPI_PASSWORD_POLICY_HIBP_PASSWORD_POLICY_APIKEY=${HIBP_API_KEY}

And referencing in the factory the following way:

public static String HIBP_API_KEY = "";
@Override
public void init(Config.Scope config) {
  HIBP_API_KEY = config.get("APIKEY");
}

Am I just doing all of this incorrectly? Thanks in advance.

System.getenv works just fine, but it won’t be specific to the SPI

What is the ID of your implementation? Specifically, which value does your getId() method of your provider return?

1 Like

The method getId() will return “HIBP”.

Then your environment variable should be KC_SPI_PASSWORD_POLICY_HIBP_APIKEY.

Additionally, perhaps(!), your code config.get("APIKEY"); must require config.get("apikey");, but I’m not sure, I never tested anything with upper case config names.

Thank you! That seems to have worked. And an FYI for anyone in the future both lowercase and uppercase of the property name worked for me.

Meaning both config.get("apikey") and config.get("APIKEY") worked.

Thus the documentation I linked to is correct. I was just confused and did not realize the <provider-id> is the ID returned from the SPI on getId(). Which now makes sense in highsight.

However, the only way knew I had to write the Docker variable in this fashion is because of this GitHub discussion.

It would be nice if there was documentation, maybe there is, stating that the format is:
KC_SPI_<SPI-ID>_<Custom-Provider-ID>_<Property>
vs.
spi-<spi-id>-<provider-id>-<property>=<value>.

Thank you for your research and attempt how to write and get env variables for SPIs.
A short hint. Keycloak documentation mentions how to write the property name spi-<spi-id>-<provider-id>-<property>=<value> as an env indirectly.

According to Configuring Keyloak it shows an example for db-url.
But somehow I agree with you that the documentation should give a hint to link I posted.

Cheers.

`