У меня есть проблема, которая, кажется, не так уж и необычна, но решения, которые я нашел, не работали в моем проекте.
Я хочу сделать простую аутентификацию с использованием паспорта, как показано в этом руководстве: https://docs.nestjs.com/techniques/authentication
Я следовал этому уроку все время, и сначала он работал. Позже я решил использовать E-Mail пользователей и пароль в качестве аутентификации вместо имени пользователя. Поэтому я изменил имена переменных и параметры в процессе аутентификации на электронную почту, и это было точкой, где все распалось. Я что-то здесь упускаю?
auth.module.ts
import {Module} from '@nestjs/common';
import {UsersModule} from "../users/users.module";
import {AuthService} from "./services/auth.service";
import {PassportModule} from "@nestjs/passport";
import {LocalStrategy} from "./strategies/local.strategy";
import {AuthController} from "./controllers/auth.controller";
import {JwtModule} from "@nestjs/jwt";
import {jwtConstants} from "./constants";
import {JwtStrategy} from "./strategies/jwt.strategy";
import {EncryptionModule} from "../encryption/encryption.module";
@Module({
imports: [
UsersModule,
EncryptionModule,
PassportModule.register({defaultStrategy: 'jwt'}),
JwtModule.register({
secret: jwtConstants.secret,
signOptions: {
expiresIn: '30s'
}
})
],
providers: [
AuthService,
LocalStrategy,
JwtStrategy
],
controllers: [
AuthController
]
})
export class AuthModule {
}
controllers / auth.controller.ts
import {Controller, Get, Post, Request, UseGuards} from '@nestjs/common';
import {AuthService} from "../services/auth.service";
import {JwtAuthGuard} from "../guards/jwt-auth.guard";
import {LocalAuthGuard} from "../guards/local-auth.guard";
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {
}
@UseGuards(LocalAuthGuard)
@Post('login')
login(@Request() req) {
return this.authService.login(req.user);
}
@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
return req.user;
}
}
services / auth.service.ts
import {Injectable} from '@nestjs/common';
import {UsersService} from "../../users/services/users.service";
import {User} from "../../users/interfaces/user.interface";
import {JwtService} from "@nestjs/jwt";
import {JwtPayloadDto} from "../models/jwt-payload.dto";
import {EncryptionService} from "../../encryption/services/encryption.service";
@Injectable()
export class AuthService {
constructor(private usersService: UsersService,
private jwtService: JwtService,
private encryptionService: EncryptionService) {
}
async validateUser(email: string, pass: string): Promise<User | undefined> {
/**
* The findOne-method sends a database query
* to my mongodb via mongoose.
* I don't think it's necessary to post the UserService here, is it?
*/
const user: User = await this.usersService.findOne(email);
return this.encryptionService.compare(pass, user.password).then((result) => {
if (result) {
return user;
}
return undefined;
});
}
async login(user: User) {
const payload: JwtPayloadDto = {
email: user.email,
sub: user.id
}
return {
accessToken: this.jwtService.sign(payload)
};
}
}
стратегии / local.strategy.ts
import {Injectable, UnauthorizedException} from "@nestjs/common";
import {PassportStrategy} from "@nestjs/passport";
import {Strategy} from "passport-local";
import {AuthService} from "../services/auth.service";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(email: string, password: string): Promise<any> {
const user = await this.authService.validateUser(email, password);
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('local') {
}
Согласно этот вопрос Я обнаружил, что сигнатура методов валидации должна иметь те же имена параметров, что и ключи полезных нагрузок запроса.
В целях отладки я поставил console.log()
-колл в первой строке моего валидатора- метод в strategies/local.strategy.ts
, но кажется, что он вообще не вызывается.
Спасибо за любой ответ заранее. Хорошего вам!