Skip to content

Dex

Not available until the next release main

Introduction

The Testcontainers module for Dex.

Adding this module to your project dependencies

Please run the following command to add the Dex module to your Go dependencies:

go get github.com/testcontainers/testcontainers-go/modules/dex

Usage example

ctx := context.Background()

dexContainer, err := dex.Run(
    ctx,
    "dexidp/dex:v2.43.1-distroless",
    // explicitly declare the issuer URL - will be used in the OpenID Connect provider configuration
    // only necessary if you want to fetch the OpenID configuration directly from the Dex instance
    // alternatively there's a convenience method that monkey patches the discovery document
    // to match the mapped port
    dex.WithIssuer("http://localhost:15556"),
    // expose the corresponding port to match the issuer URL
    testcontainers.WithExposedPorts("15556:5556/tcp"),
)
defer func() {
    if err := testcontainers.TerminateContainer(dexContainer); err != nil {
        log.Printf("failed to terminate container: %s", err)
    }
}()

if err != nil {
    log.Printf("failed to start container: %s", err)
    return
}

// Register a client application
clientApp, err := dexContainer.CreateClientApp(ctx, dex.CreateClientAppRequest{
    Name: "testcontainers-go",
})
if err != nil {
    log.Printf("failed to create client app: %s", err)
    return
}

identityReq := dex.CreatePasswordRequest{
    Email:    "ted.tester@testcontainers.com",
    Username: "ted.tester",
    Password: "$up3r$3crEt",
}

// Register an identity that can be used to authenticate with Dex
if err := dexContainer.CreatePassword(ctx, identityReq); err != nil {
    log.Printf("failed to create identity: %s", err)
    return
}

oidcCfg, err := dexContainer.OpenIDConfiguration(ctx)
if err != nil {
    log.Printf("failed to get OpenID configuration: %s", err)
    return
}

oauth2Cfg := oauth2.Config{
    ClientID:     clientApp.Id,
    ClientSecret: clientApp.Secret,
    Endpoint: oauth2.Endpoint{
        // Dex expects ClientID & Secret in the HTTP headers
        AuthStyle:     oauth2.AuthStyleInHeader,
        AuthURL:       oidcCfg.AuthorizationEndpoint,
        DeviceAuthURL: oidcCfg.DeviceAuthorizationEndpoint,
        TokenURL:      oidcCfg.TokenEndpoint,
    },
    // does not matter in this context
    RedirectURL: "http://localhost:8080/callback",
    Scopes:      []string{"openid"},
}

// the primary identifier is always the email address **not** the username 🤷‍♂️
tokenResp, err := oauth2Cfg.PasswordCredentialsToken(ctx, identityReq.Email, identityReq.Password)
if err != nil {
    log.Printf("failed to get token response: %s", err)
    return
}

fmt.Println(tokenResp.TokenType)
fmt.Println(tokenResp.Valid())

// Output:
// bearer
// true

Module Reference

Run function

  • Not available until the next release main

The Dex module exposes one entrypoint function to create the Dex container, and this function receives three parameters:

func Run(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*Container, error)
  • context.Context, the Go context.
  • string, the Docker image to use.
  • testcontainers.ContainerCustomizer, a variadic argument for passing options.

Image

Use the second argument in the Run function to set a valid Docker image. In example: Run(context.Background(), "dexidp/dex:v2.43.1-distroless").

Container Options

When starting the Dex container, you can pass options in a variadic way to configure it.

Dex OAuth2 options

You can configure the OAuth2 issuer by setting dex.WithIssuer.

Dex logging options

You can configure the Dex logging by setting dex.WithLogLevel. Valid log levels can be found in the log/slog package documentation.

The following options are exposed by the testcontainers package.

Basic Options

Lifecycle Options

Files & Mounts Options

Build Options

Logging Options

Image Options

Networking Options

Advanced Options

Experimental Options

Container Methods

The Dex container exposes the following methods:

RawOpenIDConfiguration

Fetch the OpenID Connect discovery document from the Dex container. It patches all endpoint URLs to match the container HTTP endpoint.

OpenIDConfiguration

Fetch and parse the OpenID Connect discovery document and parse it. Because it is using RawOpenIDConfiguration under the hood, the parsed endpoint URLs in the discovery document will match the mapped port of the Dex container.

CreateClientApp

Dynamically register a client application in the Dex instance by using the gRPC API. ClientID and secret will be generated if not provided.

CreatePassword

Dynamically register a new 'password' (see also staticPasswords) in Dex. Either a plaintext password or a previously computed hash can be provided. Dex expects passwords to be bcrypt encoded. To compute compatible password hashed the bcrypt library from the experimental Go packages can be used.

Note: When logging in to Dex, the email is the primary identifier, not the username.