Search code examples
nestjskeycloak

Keycloak connection error using kcAdminClient and NestJS


I am working with keycloak and using this package https://www.npmjs.com/package/@keycloak/keycloak-admin-client to implement user edit functionality for every user. Backend is written on Nest.JS. This is app.service.ts code

import { Injectable } from '@nestjs/common';
import KcAdminClient from '@keycloak/keycloak-admin-client';

@Injectable()
export class AppService {
  private adminClient: KcAdminClient;

  constructor() {
    this.getAdminProperties().then(admin => {
      this.adminClient = admin;
    })
  }

  async getAdminProperties() {
    const kcAdminClient = new KcAdminClient();

    await kcAdminClient.auth({
      username: 'user',
      password: 'user',
      grantType: 'password',
      clientId: 'admin-cli',
      
    });

    kcAdminClient.setConfig({
      realmName: 'space-realm',
    });    

    return kcAdminClient;
  }

  updateUser(body: any, id: number): any {
    this.adminClient.users.update({ id: id.toString() }, body)
  }
}

And after this all code I am getting this annoying error:

(node:732) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:8080 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)

(node:732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

Maybe I am doing something wrong?


Solution

  • The problem was inside KcAdminClient() constructor, so for dev version I just added baseUrl with static IP of my Docker container of keycloak. For dev version this approach is fine, for public also, because you will use url of you web application. Good luck!