How to import and export users to keycloak

First, I recommend setting up a backup. This way, exporting and importing users is done via backup. You would not need to recreate the realm: you can do a partial import of users into an existing realm.

My keycloak is setup with backups via docker:

version: '3.2'
services:

  keycloak:
    image: quay.io/keycloak/keycloak:23.0.3
    volumes:
      - type: bind
        source: ./volumes/backup
        target: /tmp/backup
      - type: bind
        source: ./volumes/keycloak
        target: /opt/keycloak/data/

    ports:
      - 8010:8080
    restart: always
    command: start --proxy edge --hostname-strict=false --log="console,file"
    environment:
      KEYCLOAK_ADMIN: any
      KEYCLOAK_ADMIN_PASSWORD: password

Once you run a backup, the users are backed up (exported) without passwords to a single json file. You can then use that file to do a partial realm import (in the admin console). 

keycloak: partial realm import

An example export file looks like this:

{
  "realm" : "realmname",
  "users" : [
  {
    "username" : "user-1@example.com",
    "enabled" : true,
    "totp" : false,
    "emailVerified" : false,
    "email" : "user-1@example.com",
    "credentials" : [ ],
    "disableableCredentialTypes" : [ ],
    "requiredActions" : [ ],
    "realmRoles" : [ "default-roles-realmname" ],
    "notBefore" : 0,
    "groups" : [ ]
  }, {
    "username" : "user-2@example.com",
    "enabled" : true,
    "totp" : false,
    "emailVerified" : false,
    "email" : "user-2@example.com",
    "credentials" : [ ],
    "disableableCredentialTypes" : [ ],
    "requiredActions" : [ ],
    "realmRoles" : [ "default-roles-realmname" ],
    "notBefore" : 0,
    "groups" : [ ]
  }
 ]
}

With the above info, you should be able to import and export users on a production keycloak installation.

This question has also been answered on Stack Overflow.

~ * ~ * ~ * ~

Additionally, according to Keycloak Documentation, you can perform an import of users using ReST API.

POST /admin/realms/{realm}/partialImport

First, you need to get an access_token, you can use your admin user or a client with the role manage-realm assigned

access_token=`curl http://localhost:8080/auth/realms/my-realm/protocol/openid-connect/token -XPOST -d 'grant_type=client_credentials' -u 'admin-client:admin-secret' | jq -r .access_token`

Then you can import an array of users:

curl -X POST -H "Authorization: Bearer $access_token"  -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"users":[{"username":"jose.perez","email":"jose.perez@gmail.com","firstName":"Jose","lastName":"Perez","emailVerified":true,"enabled":true,"ifResourceExists":"SKIP"}' http://localhost:8080/auth/admin/realms/my-realm/partialImport

The above method has also been suggested on Stack Overflow.

Please login or register to post a comment.