Create Cognito User Pools and public app clients, seed confirmed users and group memberships, and export runtime IDs for application tests or local development. Task types are in io.github.gregwhitaker.awsemulator.aws.cognito and use the cognito-idp service.

Run The Spring Security Example

./gradlew -p examples/cognito test --configuration-cache
./gradlew -p examples/cognito test --configuration-cache
./gradlew -p examples/cognito bootRunLocal
./gradlew -p examples/cognito stopAwsEmulator

The tests use AWS SDK v2 password sign-in and refresh, then call a Spring Boot application with signed access tokens. They check anonymous rejection, group authorization, incorrect passwords, tampered signatures, ID tokens presented as access tokens, and tokens for another client. The second invocation reuses Gradle configuration and provisions a fresh managed runtime. -PfailExample=true intentionally fails the test to exercise managed cleanup.

Important
AWS Emulator 1.0.385 signs Cognito tokens with RS256. The example’s local Spring profile explicitly allows RS256 and validates signature, issuer, expiration, token_use=access, and the configured client_id. HTTPS certificate and hostname verification stay enabled. Configure production Cognito separately with its real issuer and RS256 policy. This integration does not claim complete Cognito fidelity. See the upstream token implementation.

Supported workflows are User Pool provisioning, public clients, administrative user fixtures, groups, password sign-in, and refresh. Identity Pools, hosted login/OAuth authorization endpoints, federation, SRP, MFA, Lambda triggers, custom schema management, and confidential client creation are outside this initial integration.

Tasks And Defaults

All task types share mode (custom instances inherit awsEmulator.defaultMode, initially MANAGED) and apiCallTimeoutSeconds (default 30). They always execute against live state, with up-to-date skipping and build-cache reuse disabled. Configuration-cache reuse is supported. Applying the plugin or listing tasks does not start Docker.

Task type Properties and behavior

CreateCognitoUserPoolTask

userPoolName. Creates a pool with service defaults or reuses a uniquely named pool without changing its settings.

CreateCognitoUserPoolClientTask

userPoolName, clientName, explicitAuthFlows. Creates a public client (GenerateSecret=false), or reuses one with matching flows and no secret.

SeedCognitoUsersTask

userPoolName, fixtures JSON file, overwrite (default false). Seeds users and additive group memberships.

ExportCognitoConfigurationTask

userPoolName, clientName, outputFile. Exports current IDs, the discovered token issuer, and local connection URLs as JSON.

ListCognitoUserPoolsTask

Lists all pool names and IDs, following pagination.

DeleteCognitoUserPoolTask

userPoolName. Deletes the pool and its users, groups, and clients. Missing pools are a no-op; deletion protection and service errors remain failures.

DeleteCognitoUserPoolClientTask

userPoolName, clientName. Deletes a client; a missing pool or client is a no-op.

explicitAuthFlows defaults to ALLOW_USER_PASSWORD_AUTH, ALLOW_ADMIN_USER_PASSWORD_AUTH, and ALLOW_REFRESH_TOKEN_AUTH. It accepts a nonempty, unique subset of those three values. Reusing a client compares the complete set, ignoring order; conflicting flows or a client secret fail without modifying the client.

Pool and client IDs are generated by the emulator and resolved by exact name at execution time. Names are not assumed unique: more than one matching pool, or client within a pool, fails before selecting or deleting one. Use distinct names when configuring concurrent consumers. Client, fixture, and export tasks require their pool to exist; resource sets order the steps, or ordinary task registrations must declare dependsOn.

The convenience commands listCognitoUserPools, deleteCognitoUserPool, and deleteCognitoUserPoolClient default to DEVELOPMENT. They accept --mode=MANAGED; the deletion commands also accept --userPoolName and, for a client, --clientName:

./gradlew -p examples/cognito seedAwsEmulator
./gradlew -p examples/cognito listCognitoUserPools
./gradlew -p examples/cognito deleteCognitoUserPoolClient --userPoolName=example-users --clientName=example-app
./gradlew -p examples/cognito deleteCognitoUserPool --userPoolName=example-users
./gradlew -p examples/cognito stopAwsEmulator

Reusable Setup With Kotlin DSL

Apply the core plugin and Java plugin, then configure a resource set:

import io.github.gregwhitaker.awsemulator.aws.cognito.*
import io.github.gregwhitaker.awsemulator.model.EmulatorMode

val auth = awsEmulator.resourceSets.register("auth") {
    provision("pool", CreateCognitoUserPoolTask::class.java) {
        userPoolName.set("app-users")
    }
    provision("client", CreateCognitoUserPoolClientTask::class.java) {
        userPoolName.set("app-users")
        clientName.set("app")
    }
    seed("users", SeedCognitoUsersTask::class.java) {
        userPoolName.set("app-users")
        fixtures.set(layout.projectDirectory.file("fixtures/users.json"))
    }
    seed("configuration", ExportCognitoConfigurationTask::class.java) {
        userPoolName.set("app-users")
        clientName.set("app")
        outputFile.set(layout.buildDirectory.file(mode.map {
            "cognito/${it.name.lowercase()}.json"
        }))
    }
}
val tests = tasks.named<Test>("test") {
    systemProperty("example.cognito.configuration",
        layout.buildDirectory.file("cognito/managed.json").get().asFile.absolutePath)
}
awsEmulator {
    useWith(tests, EmulatorMode.MANAGED, auth)
    scenarios { register("default") { resources(auth) } }
}

When the Spring Boot companion is applied, add awsEmulator.springBoot.resourceSets.add(auth). Configure bootRunLocal and bootRunLocalDebug with your application’s configuration-file property pointing to build/cognito/development.json. The runnable example demonstrates both tasks. The property example.cognito.configuration belongs to that example’s reader; the plugin does not automatically configure Spring Security or application properties.

The provisioning, fixture, and export task types carry @AwsEmulatorSetupTask for the companion’s ordinary-task auto-discovery. Resource-set instances use explicit resource-set attachment instead. Separate managed and development output files prevent one runtime’s configuration from overwriting the other’s.

Ordinary Tasks With Groovy DSL

import io.github.gregwhitaker.awsemulator.aws.cognito.*

def pool = tasks.register('createAuthPool', CreateCognitoUserPoolTask) {
    userPoolName.set('app-users')
}
def appClient = tasks.register('createAuthClient', CreateCognitoUserPoolClientTask) {
    dependsOn(pool)
    userPoolName.set('app-users')
    clientName.set('app')
}
def users = tasks.register('seedAuthUsers', SeedCognitoUsersTask) {
    dependsOn(appClient)
    userPoolName.set('app-users')
    fixtures.set(layout.projectDirectory.file('fixtures/users.json'))
}
def config = layout.buildDirectory.file('cognito/managed.json')
def exported = tasks.register('exportAuth', ExportCognitoConfigurationTask) {
    dependsOn(users)
    userPoolName.set('app-users')
    clientName.set('app')
    outputFile.set(config)
}
def tests = tasks.named('test') {
    dependsOn(exported)
    systemProperty('example.cognito.configuration', config.get().asFile.absolutePath)
}
awsEmulator { useWith(tests) }

For ordinary task registrations targeting a persistent instance, select EmulatorMode.DEVELOPMENT on every resource task in the dependency chain and choose a development-specific output path.

User Fixtures And Repeat Runs

fixtures/users.json
[
  {
    "username": "alice",
    "password": "Local-Test123!",
    "attributes": {"email": "alice@example.test", "email_verified": "true"},
    "groups": ["admins"]
  }
]

The file is a nonempty JSON array, limited to 16 MiB. Each entry requires username and password; attributes is an optional string-to-string object, and groups is an optional array of unique group names. Unknown fields, duplicate JSON keys, duplicate usernames, invalid shapes, and the immutable sub attribute are rejected before the seeding task opens its connection or modifies users. The service enforces its password policy and supported attribute names. Use local test credentials; passwords are read during execution and are not printed.

New users are created with invitations suppressed and a permanent password, making them confirmed without an email/SMS confirmation flow. Missing groups are created with default settings; memberships are added. Existing group settings, unrelated attributes, users, and memberships are preserved.

With overwrite=false, an existing enabled, confirmed user is reused only when all explicitly requested attributes match. The existing password is retained: Cognito cannot return a password for comparison, so changing only the fixture password has no effect on a reused user. With overwrite=true, supplied attributes are updated and the permanent password is reset on each run. Disabled users always fail and require explicit re-enabling. An existing unconfirmed user requires overwrite=true to set its permanent password.

All entries are parsed and validated before SDK calls. Service failures can leave earlier entries or a newly created user in place; errors report the failing entry number and completed count without fixture values. After fixing a failure during password assignment, rerun with overwrite=true to complete the user. The task does not roll back or delete unrelated resources.

Consume Generated Configuration

ExportCognitoConfigurationTask writes these fields:

Field Meaning

userPoolId

The selected pool’s actual ID.

clientId

The selected app client’s actual ID.

region

The runtime’s configured region.

endpoint

The local HTTPS SDK endpoint.

issuer

The issuer advertised by the pool’s discovery document, fetched over verified HTTPS from the local emulator. The default in 1.0.385 is https://cognito-idp.<region>.amazonaws.com/<userPoolId>; an UPDATED pool uses issuer-cognito-idp instead.

jwksUri

The local emulator endpoint followed by /<userPoolId>/.well-known/jwks.json. Key retrieval stays local even when the issuer names an AWS hostname.

The issuer is a value to validate in token claims, not a network destination. Discovery and JWKS requests use the configured emulator endpoint; the export does not follow redirects or the discovery document’s advertised remote URLs. Missing or malformed issuer metadata fails the task. Older emulators that advertise a local issuer are supported through the same discovery path.

The output contains no credentials, passwords, tokens, or client secrets. It is replaced atomically where supported and uses owner-only permissions on POSIX filesystems. The file survives the task; its IDs become stale when that emulator stops. Always depend on the export and read it in the consuming process after setup. Do not parse it during Gradle configuration or hardcode generated IDs. Each managed invocation exports fresh IDs, including when the configuration cache is reused.

Applications declare their own software.amazon.awssdk:cognitoidentityprovider dependency and use the normal SDK endpoint, credential, and TLS providers supplied to opted-in consumers. The example reads this JSON in application code and configures NimbusJwtDecoder with the local JWKS URI. It does not disable JWT or TLS validation or modify the Gradle daemon’s global settings.