#Authentication guard not working as expected

42 messages · Page 1 of 1 (latest)

stray gorge
#

Here is my NestJS auth practice project, I have created iam directory and there with help of access-token.guard.ts I want to verify access token, then I wanted to create a custom decorator @Auth to declare some routes as public that's why created another guard authorization.guard.ts, But it's not working, without using this decorator, I should have got 401 unauthorized response, but I am getting 200 ok response. What i am doing wrong here? I am giving the iam.module.ts file here, and authorization.guard.ts file in picture

// iam.module.ts

@Module({
  imports: [
    TypeOrmModule.forFeature([User]),
    JwtModule.registerAsync(jwtConfig.asProvider()),
    ConfigModule.forFeature(jwtConfig),
  ],
  providers: [
    {
      provide: HashingService,
      useClass: BcryptService,
    },
    {
      provide: APP_GUARD,
      useClass: AuthenticationGuard,
    },
    AccessTokenGuard,
    AuthenticationService,
  ],
  controllers: [AuthenticationController],
})
export class IamModule {}
#

I get 200 ok response even I dont give any Bearer token now

silver belfry
#

And the IamModule is imported into the AppModule?

stray gorge
#

yes

#

// app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CoffeesModule } from './coffees/coffees.module';
import { UsersModule } from './users/users.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { IamModule } from './iam/iam.module';

@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      useFactory: () => ({
        type: 'postgres',
        host: process.env.DATABASE_HOST,
        port: +process.env.DATABASE_PORT,
        username: process.env.DATABASE_USER,
        password: process.env.DATABASE_PASSWORD,
        database: process.env.DATABASE_NAME,
        autoLoadEntities: true,
        synchronize: true, // disable for production
      }),
    }),
    IamModule,
    CoffeesModule,
    UsersModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

silver belfry
#

What is the authTypes that is being printed out during the request?

stray gorge
#

[0]

silver belfry
#

this.authTypeGuardMap[0] doesn't bring back any guards, right?

stray gorge
#

I have to see this with console.log

silver belfry
#

Can you provide a minimum reproduction so I can debug this locally? This seems strange

stray gorge
#

this code is hosted in a public repo can I share that?

silver belfry
#

How hard is it to run the repo? How complex is it?

stray gorge
#

its simple

#

just basic auth

silver belfry
#

Is it possible to remove the database portion for the sake of simple debugging?

stray gorge
#

or can we use the live share vs code?

#

I can give you access

silver belfry
#

I would much rather be able to simply run it locally. It looks like the DB shouldn't be necessary for debugging this, hence why I'm asking for it not to be there

#

I already said no to a live share

stray gorge
#

okay sorry

#

yeah db is not necessary to resolve the issue

stray gorge
#

I am surprised to have this issue, If I do not use the AuthenticationGuard in iam.module.ts then it works properly like it gives 401 unauthrized response, but when I use AccessTokenGuard, even if I don't give the Bearer token in request, it gives 200 ok response

silver belfry
#

It probably depends on what guards are being checked against

#

That's why I asked what guards are being used

stray gorge
#

the purpose of this AuthenticationGuard was to use a custom decorator to use it on sign-in and sign-up routes, as these routes should not have AccessTokenGuard

silver belfry
#

I'm not sure I follow with the current implementation

silver belfry
#

If you can modify your repo to not include the DB I will take a look

stray gorge
#

Okay I am removing db dependencies

stray gorge
#

I have removed db dependency

#

Plase take a look if you can

silver belfry
#

What route do you want me to hit?

stray gorge
#

sign-in

silver belfry
#

Your canActivate in your guard is getting assigned a value, making it truthy even though the value assigned is an error, so you're returning true at the first truthy value, and short-circuiting the guard

stray gorge
#

I followed the Authentication and Authorization course by NestJS Team

silver belfry
#
    for (const instance of guards) {
      const canActivate = await Promise.resolve(
        instance.canActivate(context),
      ).catch((err) => (error = err));
      console.log(canActivate);
      if (canActivate) return true;
    }

This is where I'm talking about the canActivate being set to a truthy value

#

I've not personally gone through the course Kamil created, so I am unaware of what you specifcially have watched/understood

stray gorge
#

so what should be the right approach?

#

I should have got unauthorized error if I do not use @Auth decorator and set it to none

silver belfry
#

I would suggest not Promise.resolve()ing, as that will always resolve the value even if it's an error

#

I would also not early return unless you want to short circuit