NodeJS Nest.JS -全局身份验证保护

qpgpyjmq  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(135)

我想在My NestJS应用程序中实现一个全局身份验证保护,它将简单地读取某些头部并根据这些头部为每个请求分配用户值。
我实现了这个简单的逻辑,并在我的主模块中注册了我的全局守护程序,但是由于某种原因,我所有的请求都失败了,并显示“401 Unauthorized”。我尝试将日志消息放在internal.strategy.ts中,但是我没有看到它们被调用。
你知道为什么策略没有被调用吗?
这是我的main.ts

import { NestFactory, Reflector } from '@nestjs/core';
import * as logging from './logging';
import { AppModule } from './app.module';
import config from './config';
import { LocalAuthGuard } from './auth/guards/local-auth.guard';

async function bootstrap(port: string | number) {
  const app = await NestFactory.create(AppModule);
  app.useGlobalGuards(new LocalAuthGuard())
  await app.listen(port, '0.0.0.0');

  logging.logger.info(`Listening on 0.0.0.0:${port}`);
}

bootstrap(config.port);

这是我的auth.module.ts

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { InternalStrategy } from './stategies/internal.strategy';

@Module({
  imports: [PassportModule],
  providers: [AuthService, InternalStrategy ]
})
export class AuthModule {}

这是我的auth.service.ts

import { Injectable } from '@nestjs/common';
import { Role } from 'src/workspaces/interfaces/models';

@Injectable()
export class AuthService {
    validateUser(headers: Headers): any {
        const workspaceId = headers['workspace-id'];
        const workspaceRole = Role[headers['workspace-role']];

        return {
            workspaceId: workspaceId,
            workspaceRole: workspaceRole
        }
    }
}

这是我的internal.strategy.ts

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';

@Injectable()
export class InternalStrategy extends PassportStrategy(Strategy, 'internal') {
  constructor(private authService: AuthService) {
    super({ passReqToCallback: true });
  }

  async validate(req: Request): Promise<any> {
    console.log('Validate internal strategy')
    const user = await this.authService.validateUser(req.headers);
    if (!user) {
      throw new UnauthorizedException();
    }
    
    return user;
  }
}

以下是我的local-auth.guard.ts

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('internal') {}
wvt8vs2t

wvt8vs2t1#

在依赖注入方面,从任何模块外部注册的全局守卫都不能注入依赖,因为这是在任何模块的上下文之外完成的。为了解决这个问题,您可以使用以下结构直接从任何模块设置防护:
请阅读nestjs文档。https://docs.nestjs.com/guards#binding-guards

import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: LocalAuthGuard,
    },
  ],
})
export class AppModule {}

相关问题