Using Postman to test my endpoints, I am able to successfully "login" and receive a JWT token. Now, I am trying to hit an endpoint that supposedly has an AuthGuard
to ensure that now that I am logged in, I can now access it.
However, it constantly returns 401 Unauthorized
even when presented the JWT token in Postman.
Here is my code:
user.controller.ts
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@UseGuards(AuthGuard())
@Get()
getUsers() {
return this.usersService.getUsersAsync();
}
}
jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authenticationService: AuthenticationService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'SuperSecretJWTKey',
});
}
async validate(payload: any, done: Function) {
console.log('I AM HERE'); // this never gets called.
const user = await this.authenticationService.validateUserToken(payload);
if (!user) {
return done(new UnauthorizedException(), false);
}
done(null, user);
}
}
I have tried ExtractJWT.fromAuthHeaderWithScheme('JWT')
as well but that does not work.
authentication.module.ts
@Module({
imports: [
ConfigModule,
UsersModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: 'SuperSecretJWTKey',
signOptions: { expiresIn: 3600 },
}),
],
controllers: [AuthenticationController],
providers: [AuthenticationService, LocalStrategy, JwtStrategy],
exports: [AuthenticationService, LocalStrategy, JwtStrategy],
})
export class AuthenticationModule {}
authentication.controller.ts
@Controller('auth')
export class AuthenticationController {
constructor(
private readonly authenticationService: AuthenticationService,
private readonly usersService: UsersService,
) {}
@UseGuards(AuthGuard('local'))
@Post('login')
public async loginAsync(@Response() res, @Body() login: LoginModel) {
const user = await this.usersService.getUserByUsernameAsync(login.username);
if (!user) {
res.status(HttpStatus.NOT_FOUND).json({
message: 'User Not Found',
});
} else {
const token = this.authenticationService.createToken(user);
return res.status(HttpStatus.OK).json(token);
}
}
}
In Postman, I am able to use my login endpoint to successfully login with the proper credentials and receive a JWT token. Then, I add an Authentication
header to a GET request, copy and paste in the JWT token, and I have tried both "Bearer" and "JWT" schemes and both return 401 Unauthorized
as you can see in the images below.
I used the JWT.IO debugger, to check if there's anything wrong with my token and it appears correct:
I am at a lost as to what could be the issue here. Any help would be greatly appreciated.