我使用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的用户名和密码是必须的,其他属性是可选的。