使用电子邮件进行身份验证时,NestJS护照身份验证会返回401

时间:2020-04-06 19:06:08

标签: authentication passport.js nestjs passport-local

我遇到的问题似乎并不罕见,但是我发现的解决方案在我的项目中不起作用。

我想做的是使用护照进行简单的身份验证,如本教程所示:https://docs.nestjs.com/techniques/authentication

我一直遵循本教程,起初它是有效的。后来我决定使用用户的电子邮件和密码代替用户名作为身份验证。因此,我在身份验证过程中将变量名和参数更改为电子邮件,这就是一切都破裂的地方。我在这里想念东西吗?

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)
        };
    }
}

strategies / 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;
    }
}

guards / local-auth.guard.ts

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

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

根据this question,我发现validate-methods签名必须具有与请求有效负载密钥相同的参数名称。

出于调试目的,我在console.log()的validate方法的第一行进行了一次strategies/local.strategy.ts调用,但似乎根本没有调用。

感谢您提前提出任何答案。 有一个好吧!

2 个答案:

答案 0 :(得分:2)

对我来说,在创建 LocalStrategy 时,我将 {usernameField: 'email'} 传递给了 ParentClass。

如果您想使用“电子邮件”等自定义列检查用户身份验证,请尝试通过它。

我的 user.entity.ts:

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  email: string;

  @Column()
  name: string;
}

我的 local.strategy.ts:

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email' });
  }

  async validate(email: string, password: string): Promise<User> {
    console.log(email, password); // it works
  }
}

答案 1 :(得分:0)

好吧,我自己解决了。 5个小时的调试浪费了! 原来,我的邮递员以某种方式没有随请求发送Content-Type标头。重新启动Postman修复了它。