Search code examples
node.jskeycloakhapi

invalid json response body at http://localhost:8080/auth/admin/realms/RealmName/users reason: Unexpected end of JSON input


user.js:(In keycloak_add_user, i need to get proper response id of the user added in the keycloak. But user is successfully added, but getting this response, so not able to assign role for the user. Please help if any changes required for my code?)

 const payload = {
                email: req.payload.email,
                firstName: req.payload.first_name,
                lastName: req.payload.last_name,
                credentials: [
                    {
                        type: 'password',
                        temporary: false,
                        value: req.payload.password,
                    },
                ],
                enabled: true,
                emailVerified: true,
                createdTimestamp: Date.now(),
                requiredActions: ['UPDATE_PASSWORD'],
            };
          const token = req.headers.authorization;
        const keycloak_add_user = await fetch(
                     `http://${process.env.KEYCLOAK_HOST}:${process.env.KEYCLOAK_PORT}/auth/admin/realms/${process.env.REALM_NAME}/users`,
                        {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                Authorization: token,
                            },
                            body: JSON.stringify(payload),
                        }
                    );
               console.log('keycloak_add_user',keycloak_add_user)
            if (keycloak_add_user.status !== 201 || !keycloak_add_user) {
                return h
                    .response({ error: keycloak_add_user.statusText })
                    .code(keycloak_add_user.status);
            }
            const keycloak_user = await keycloak_add_user.json();
            console.log('keycloak_user', keycloak_user)

response:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'http://13.213.9.103:8080/auth/admin/realms/Rubick/users',
    status: 201,
    statusText: 'Created',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

Solution

  • You need to call a new user GET call after adding user. The adding user POST call did not response a new user's id. it returned just 201 Created status.

    This node java script is example to get new user id.

    import fetch from "node-fetch";
    
    const displayUserId = async () => {
        const token ='eyJhbGciOiJSUzI1NiIsInR5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a1eKzo6Rfnh4387vyai80kFPUN2mb4x20xOw';
        const got = await fetch('http://localhost:8080/auth/admin/realms/test/users/?username=newmyuser',
            {
                method: 'GET',
                headers: {
                    'Content-Type' : 'application/json',
                    Authorization: 'Bearer ' + token
                }
            }
        );
        const response = await got.json();
        console.log(response);
        console.log(response.map(({ id }) => ({ id })))
    }
    displayUserId();
    

    And it's display a response in terminal.

    $ node get-api.js
    [
      {
        id: '70fb1f9f-257d-4f11-8e3d-b0e01bafa47f',
        createdTimestamp: 1655395295332,
        username: 'newmyuser',
        enabled: true,
        totp: false,
        emailVerified: false,
        firstName: 'newFirstName',
        lastName: 'newLastName',
        email: '[email protected]',
        disableableCredentialTypes: [],
        requiredActions: [],
        notBefore: 0,
        access: {
          manageGroupMembership: true,
          view: true,
          mapRoles: true,
          impersonate: false,
          manage: true
        }
      }
    ]
    [ { id: '70fb1f9f-257d-4f11-8e3d-b0e01bafa47f' } ]