Interface CredentialsProvider

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface CredentialsProvider
Supplies the credentials to connect with, every time a connection is made.

Consulted on every connection attempt, not once at start-up. That is the whole reason this is an interface rather than two strings, and it is the detail most clients get wrong. A token has an expiry. A client that reads one at start-up works beautifully for fifty-nine minutes and then cannot reconnect — at three in the morning, looking exactly like a broker fault, because the broker is the thing rejecting it.

Implementations must therefore be cheap to call and safe from many threads. Fetching from a vault belongs behind a short cache inside the implementation, not in a field read once.

  • Method Details

    • get

      Returns:
      the credentials to use for the connection about to be made
      Throws:
      SecurityConfigurationException - if they cannot be obtained
    • of

      static CredentialsProvider of(String username, String password)
      Fixed credentials.

      Fine for a test and for a password that genuinely never rotates. Anything read from a vault or an identity provider should not use this, because it will be read once.

      Parameters:
      username - the user
      password - its password
      Returns:
      a provider returning them
    • fromEnvironment

      static CredentialsProvider fromEnvironment(String usernameVariable, String passwordVariable)
      Credentials from environment variables, re-read each time.

      Re-reading matters: a sidecar that rotates a secret by rewriting the environment of a restarted process is common, and so is one that rewrites a mounted file.

      Parameters:
      usernameVariable - name of the variable holding the user
      passwordVariable - name of the variable holding the password
      Returns:
      a provider reading them on every call
    • fromFile

      static CredentialsProvider fromFile(Path file)
      Credentials from a properties file, re-read each time.

      For a secret mounted as a file, which is how Kubernetes and most vault agents deliver one. Re-reading is the point: the file is rewritten in place when the secret rotates, and a provider that cached it would keep presenting the old one.

      Parameters:
      file - a properties file holding username and password
      Returns:
      a provider reading it on every call