0

Nest-Keycloak-connect is protecting all DTOs, Public() Decorator not working when querying a housing. Getting always Unauthorized when i want to query public items.

import { ID, ObjectType } from "@nestjs/graphql";
import { FilterableField, Relation } from "@ptc-org/nestjs-query-graphql";
import { Public, Unprotected } from "nest-keycloak-connect";
import { PropertyDTO } from "../property/property.dto";

@Public()
@ObjectType("Housing")
@Relation("property",() => PropertyDTO,  {disableRemove: true})
export class HousingDTO {
    @FilterableField(() => ID)
    id !: number
}

Housing Module

import { Module } from "@nestjs/common";
import { NestjsQueryGraphQLModule } from "@ptc-org/nestjs-query-graphql";
import { NestjsQueryTypeOrmModule } from "@ptc-org/nestjs-query-typeorm";
import { HousingDTO } from "./housing.dto";
import { HousingEntity } from "./housing.entity";
import { HousingInputDTO } from "./housing.input.dto";

@Module({
    imports: [
      NestjsQueryGraphQLModule.forFeature({
        imports: [NestjsQueryTypeOrmModule.forFeature([HousingEntity])],
        resolvers: [{
          DTOClass: HousingDTO, 
          EntityClass: HousingEntity,
          CreateDTOClass: HousingInputDTO,
        }]
      })
    ],
    
  })
  export class HousingModule {}

Keycloak configured and working when logged in. But i need also to query the housing when not logged in.

@Module({
  imports: [
    ....
    HousingModule,
    ....
    KeycloakConnectModule.register({
      authServerUrl: 'https://auth.xxx.com/auth/',
      realm: 'xxx',
      clientId: 'xxx',
      secret: process.env.KEYCLOAK_SECRET,   
      policyEnforcement: PolicyEnforcementMode.PERMISSIVE, // optional
      tokenValidation: TokenValidation.ONLINE, // optional
      logLevels: ['warn', 'error'],
    }),
  ],
  providers:   [
    {
      provide: APP_GUARD,     
      useClass: AuthGuard,
    },
    {
      provide: APP_GUARD,
      useClass: ResourceGuard,
    },
    {
      provide: APP_GUARD,
      useClass: RoleGuard,
    }
  ],
})
export class AppModule {}

1 Answers1

0

It won't work, because you must use the Public decorator on the endpoints.

Simply put the decorator on one of your controller endpoints to achieve the unauthenticated access.

Example for that:

import { Resource, Roles, Scopes, Public, RoleMatchingMode } from 'nest-keycloak-connect';
import { Controller, Get, Delete, Put, Post, Param } from '@nestjs/common';
import { Product } from './product';
import { ProductService } from './product.service';

@Controller()
@Resource(Product.name)
export class ProductController {
  constructor(private service: ProductService) {}

  /**
   * if you use decorator here, the endpoint will
   * be accessible without authentication
   **/
  @Get()
  @Public() // <-- Used here
  async findAll() {
    return await this.service.findAll();
  }
}

You can read more here.

csakbalint
  • 698
  • 7
  • 16