Search code examples
typescriptnestjskeycloakkeycloak-nodejs-connect

How to extend AuthGaurd Class Imported from 'nest-keycloak-connect'


I am using nest-keycloak-connect in nestjs and I want to create my own class extends from AuthGuard class for some custom functionality

I tried and it works well


  @Injectable()
  export class KeycloakAuthGuard extends AuthGuard implements CanActivate {
    canActivate(context: ExecutionContext) {
        const value = super.canActivate(context);
        const [request] = extractRequest(context);
        console.log(' ++++++++++++++++++ ++++++++++++++ ', request.user); //getting user here

        // Some Custom functionality here..... like call any external request

        return value;
    }
  }

But I need to add a constructor so that I can use some services here like HttpService Can anyone please help me out how can I?

constructor(private http: HttpService) { super() //contructor requires 4 arguments }

if I give constructor params like

constructor(
        private http: HttpService,
        @Inject(KEYCLOAK_INSTANCE)
        private keycloak: any,
        @Inject(KEYCLOAK_CONNECT_OPTIONS)
        private keycloakOpts: any,
        @Inject(KEYCLOAK_LOGGER)
        private logger: Logger,
        private readonly reflector: Reflector,
    ) {
        super(
            keycloak,
            keycloakOpts,
            logger,
            reflector
        );
    }

I encountered this error

Class 'KeycloakAuthGuard' incorrectly extends base class 'AuthGuard'. Types have separate declarations of a private property 'keycloak'.

class AuthGaurd Code you may find here: https://github.com/ferrerojosh/nest-keycloak-connect/blob/master/src/guards/auth.guard.ts

nest-keycloak-connect package https://www.npmjs.com/package/nest-keycloak-connect


Solution

  • Ok, so what I got from the library author is

    Rename the constructor properties since they will conflict with the superclass.

    constructor(
      @Inject(KEYCLOAK_INSTANCE)
      private keycloak1: any
      @Inject(KEYCLOAK_CONNECT_OPTIONS)
      private keycloakOpts1: any,
      @Inject(KEYCLOAK_LOGGER)
      private logger1: Logger,
      private readonly reflector1: Reflector
    )