Skip to content

Instantly share code, notes, and snippets.

@goeh
Created November 29, 2019 12:00
Show Gist options
  • Save goeh/fe35c1ac9d0c1e5aae5579b24db486e3 to your computer and use it in GitHub Desktop.
Save goeh/fe35c1ac9d0c1e5aae5579b24db486e3 to your computer and use it in GitHub Desktop.
Inject client secrets from a local file into a Keycloak Realm Export (JSON) file
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def jsonSlurper = new JsonSlurper()
def secrets = jsonSlurper.parse(new File(args[1] ?: "secrets.json")).clients.inject([:]) { map, c -> map[c.client] = c.secret; map }
def realm = jsonSlurper.parse(new File(args[0]))
for(client in realm.clients) {
if(secrets[client.clientId]) {
client.secret = secrets[client.clientId]
}
}
def output = JsonOutput.toJson(realm)
def json = JsonOutput.prettyPrint(output)
println json
@goeh
Copy link
Author

goeh commented Nov 29, 2019

Keycloak does not export client secrets, but it can import them. So if you need to import a realm with known secrets you can export the realm first, then use this groovy script to replace ********** in the json file with secrets from a secrets.json file that you prepared.

Example secrets.json

{
  "clients": [
    { "client": "customer-service", "secret": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" },
    { "client": "book-service", "secret": "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy" }
  ]
}

Usage: groovy set-keycloak-client-secret.groovy realm-export.json secrets.json > realm-export-new.json

@graubitz
Copy link

Thanks goeh, you saved my day !!! Really cool idea.

@ikromnurrohim
Copy link

Thanks, very cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment