【问题标题】:Permission to endpoint端点权限
【发布时间】:2021-04-08 11:52:29
【问题描述】:

我创建了自定义装饰器以在我的嵌套应用程序中的每个控制器上进行身份验证,如下所示:

export function AuthRequired(exposeOptions?: ExposeOptions): (arg0: Controller, arg1: string, arg3: TypedPropertyDescriptor<unknown>) => void {
  const exposeFn = Expose(exposeOptions);
  const apiBearerAuthFn = ApiBearerAuth();
  const guardFn = UseGuards(AuthGuard())


  return function (target: Controller, key: string, descriptor: TypedPropertyDescriptor<unknown>): void {
    apiBearerAuthFn(target, key, descriptor);
    guardFn(target, key, descriptor);
    exposeFn(target, key);
  }
}

但它不起作用,我有权访问我的所有端点:/ 大摇大摆地看起来像这样:

这个挂锁必须关好

谁能告诉我我哪里错了?

下面是我的完整代码:

身份验证服务

@Injectable()
export class AuthService {
  constructor(
      private jwtService: JwtService,
      private userService: UserService,
      private conn: Connection
    ) {}

  private async validate(userData: UserCredentials): Promise<boolean> {
    const user = this.userService.getUserByUsername(userData.username);
    if(user) {
      const isUserCorrect = await this.checkUserPassword(userData);
      if(isUserCorrect) return true;
    } else {
      throw new BadRequestException('User does not exist!');
    }
  }

  public async login(userData: UserCredentials): Promise< any | { status: number }>{
    const isLogged = await this.validate(userData);

    if(isLogged) {
      const user = await this.userService.getUserByUsername(userData.username);
      let payload = `${user.username}${user.id}${user.userType}`;
      const accessToken = this.jwtService.sign(payload);

      return {
        userId: user.id,
        accessToken: accessToken
      }
    }
  }

  public async register(user: UserModel): Promise<any>{
      return this.userService.addUser(user)
  }

  async checkUserPassword(credentials: UserCredentials): Promise<boolean> {
    const user = await this.conn.getRepository(User).findOneOrFail({ username: credentials.username, password: createHmac('sha256', credentials.password).digest('hex') }).catch(() => {
        throw new NotFoundException('Bad password or user does not exist!');
      }
    );

    if(user) return true;
  }
}

授权模块

@Module({
    imports: [
        TypeOrmModule.forFeature([User]),
        PassportModule.register({ defaultStrategy: 'jwt' })
    ],
    providers: [UserService],
    exports: [PassportModule]
})
export class AuthModule { }

应用模块

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ///
    }),
    JwtModule.register({
      secret: 'secretKey'
    }),
    AuthModule,
    UserModule,
  ],
  controllers: [AppController, UserController, AuthController],
  providers: [AppService, UserService, AuthService],
})
export class AppModule {}

应用控制器

    @Get()
    @AuthRequired()
    async getCurrentUser() {
        console.log();
    }

我不知道出了什么问题:/

大摇大摆:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const options = new DocumentBuilder()
    .setTitle('title')
    .setDescription('desc')
    .setVersion('0.1')
    .addServer('/api', 'Main server - current/local')
    .build();
  
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-doc', app, document);

  app.setGlobalPrefix('api');

  
  await app.listen(3000);
}
bootstrap();

【问题讨论】:

  • 你能告诉我们你是如何使用DocumentBuilder初始化swagger的吗?
  • @eol:我把代码贴在主帖底部,你能看一下吗?

标签: javascript typescript express nestjs


【解决方案1】:

根据documentation,您缺少DocumentBuilder 上的安全定义。尝试添加以下内容:

const options = new DocumentBuilder()
    .setTitle('title')
    .setDescription('desc')
    .setVersion('0.1')
    .addServer('/api', 'Main server - current/local')
    .addBearerAuth() // <-- note this
    .build();

【讨论】:

  • @OP:有什么反馈吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
相关资源
最近更新 更多