Max
Max

Reputation: 176

NestJS passport authentication returns 401 when using email for authentication

I have a problem that seems to be not that uncommon, but the solutions that I found did not work in my project.

What I want to do is a simple authentication using passport as this tutorial suggests: https://docs.nestjs.com/techniques/authentication

I followed this tutorial all along and at first it worked. Later I decided to use the users E-Mail and password as authentication instead of a username. So I changed my variable names and parameters in the authentication process to email and that was the point where everything broke apart. Am I missing something here?

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') {
}

According to this question I found out that the validate-methods signature has to have the same parameter names as the request payloads keys.

For debugging purposes I have put a console.log()-call on the first line of my validate-method in the strategies/local.strategy.ts but it seems as it does not get called at all.

Thanks for any answer in advance. Have a good one!

Upvotes: 7

Views: 6923

Answers (2)

blue-hope
blue-hope

Reputation: 3259

for me, when create LocalStrategy, I passed {usernameField: 'email'} to ParentClass.

If you want to check user authenticate with custom column like 'email', try pass it.

my user.entity.ts:

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

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

  @Column()
  name: string;
}

my 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
  }
}

Upvotes: 21

Max
Max

Reputation: 176

Well, I solved it myself. 5 hours of debugging wasted! Turned out that somehow my Postman did not send the Content-Type header with the request. Restarting Postman fixed it.

Upvotes: 2

Related Questions