I'm trying to use JWT to authenticate my users in my NestJS API but I always get the same error: Unauthorized 401.
Let me show you my code before I tell you about my investigation that came up empty:
JWT generation (this code works correctly)
auth.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { UserModule } from 'src/user/user.module';
import { AuthService } from './auth.service';
import { LocalAuthController } from './local/local-auth.controller';
import { JwtStrategy } from './jwt/jwt.strategy';
@Module({
imports: [
ConfigModule,
JwtModule.register({
secretOrPrivateKey: 'a'
}),
UserModule],
providers: [AuthService, JwtStrategy],
controllers: [LocalAuthController]
})
export class AuthModule {}
auth.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import * as bcrypt from 'bcrypt';
import { LocalAuthDto } from './local/local-auth.dto';
import { AccountType, User } from 'src/user/entity/user.entity';
import { JwtPayload } from './jwt/jwt.payload';
import { JwtService } from '@nestjs/jwt';
@Injectable()
export class AuthService {
constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService,
) {}
async signinLocal(localAuthDto: LocalAuthDto): Promise<any | null> {
const user = await this.userService.findOneByEmailOrUsername(localAuthDto.emailOrUsername, true);
if (user === null || !(await bcrypt.compare(localAuthDto.password, user.password)))
throw new UnauthorizedException("Invalid credentials");
const payload: JwtPayload = { sub: user.uuid };
return this.jwtService.sign(payload);
}
}
local-auth.controller.ts
import { Body, Controller, Post, Request, UnauthorizedException, UseGuards } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { AuthService } from '../auth.service';
import { LocalAuthDto } from './local-auth.dto';
@ApiTags("auth")
@Controller('auth/local')
export class LocalAuthController {
constructor(private readonly authService: AuthService) {}
@Post('signin')
async signin(@Body() localAuthDto: LocalAuthDto) {
return await this.authService.signinLocal(localAuthDto);
}
}
jwt.payload.ts
export class JwtPayload {
sub: string;
}
JWT Usage (this doesnt work)
jwt.strategy.ts
import { Injectable, Logger, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt } from "passport-jwt";
import { Strategy } from "passport-local";
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: true,
secretOrKey: 'a',
});
}
async validate(payload: any) {
return payload;
}
}
jwt.guard.ts
import { Injectable, Logger, UnauthorizedException } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
private readonly logger = new Logger(JwtAuthGuard.name);
handleRequest(err, user, info) {
this.logger.error(err, user, info);
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
Where I use the JwtAuthGuard
app.controller.ts
import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard as JwtAuthGuard } from './auth/jwt/jwt.guard';
@Controller()
export class AppController {
constructor() {}
@Get()
healthCheck(): string {
return "API started";
}
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@Get("authCheck")
authenticationGuardCheck(): string {
return "It works";
}
}
My investigation
First I extracted a generated JWT by my code :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIwNGRkM2MyNi03YjA4LTQ2MWEtYTA4OS05YWRkOTgzZjZmODUiLCJpYXQiOjE2NzA3NzU2MzR9.0MuojBY0_i5Losa6IgPrB2A2py-XrLoueMc4Mk1PUrY
It contains the good uuid and is well signed with the secret: a
Passport did not give me any errors in the console and just returned me Unauthorized 401
So I tried to display more informations and i found this code (in jwt.guard.ts):
handleRequest(err, user, info) {
this.logger.error(err, user, info);
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
Now when I send a request i get this into the console : passport "errors"
So I ask NestJS to print my requests and my token is present: request header
And now I'm stuck here, I don't understand why passport cant get my token in the request headers. You are my last chance ;(
Thanks for the help
CodePudding user response:
In your JwtStrategy
you import Strategy
from passport-local
instead of passport-jwt
. This means that passport is looking for req.body.username
and req.body.password
instead of actually caring about the JWT
you are sending via the authorization
header. Import Strategy
from passport-jwt
instead and this should be resovled