LocalAuthGuard不工作在nestjs应用与typeform和passportlocal

2022-01-30 15:07:44 标签 passport.jsnestjspassport-local

我使用nestjs 8。0类型的护照-jwt和护照-本地。除了LocalAuthGuard之外,一切似乎都工作得很好。我能够成功地创建一个新用户,甚至使用有JwtAuthGuard的路由,但LocalAuthGuard似乎有一些问题,因为我一直得到401未经授权的错误

还有一种方法,控制台日志一些输出从LocalAuthGuard或LocalStrategy?

auth。controller。ts

@Controller(['admin', 'user'])
export class AuthController {
  constructor(
    private authService: AuthService,
  ) {}
  @UseGuards(LocalAuthGuard)
  @Post('login')
  login(@Request() req) {
    console.log('object');
    if (req.path.includes('admin') && !req.user.isAdmin) {
      throw new UnauthorizedException();
    }
    return this.authService.login(req.user);
  }
...
}

local。guard。ts

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}

local。strategy。ts

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super();
  }
  async validate(usernameOrEmail: string, password: string): Promise<any> {
    const user = await this.authService.validateUser({
      usernameOrEmail,
      password,
    });
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

auth。service。ts

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private jwtService: JwtService,
  ) {}
  async validateUser({ usernameOrEmail, password }: LoginDto) {
    const user = (await this.userRepository.findOne({ username: usernameOrEmail })) ||
  (await this.userRepository.findOne({ email: usernameOrEmail }));
    if (user && (await bcrypt.compare(password, user.password))) {
      return user;
    }
    return null;
  }
...
}

auth。module。ts

@Module({
  imports: [
    TypeOrmModule.forFeature([User]),
    PassportModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        return {
          secret: configService.get('JWT_KEY'),
          signOptions: {
            expiresIn: '6000s',
          },
        };
      },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService],
  controllers: [AuthController],
})
export class AuthModule {}

非常感谢任何帮助或建议。

编辑

似乎LocalAuthGuard的用户名和密码是必须的,其他属性是可选的。

阅读全文

▼ 版权说明

相关文章也很精彩
推荐内容
更多标签
相关热门
全站排行
随便看看

错说 cuoshuo.com —— 程序员的报错记录

部分内容根据CC版权协议转载;网站内容仅供参考,生产环境使用务必查阅官方文档

辽ICP备19011660号-5

×

扫码关注公众号:职场神器
发送: 1
获取永久解锁本站全部文章的验证码