I am running into an error when trying to send a post request through postman to my server in order to enter a new user into my database. I am using environment variables to place the secret key in all of the necessary places. The error is saying that my secretOrPrivateKey has no value, although I have checked through logging in the console that it is providing the key I am using. I have also tried hard coding a value into the source code, and that has also not worked.
jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UsersService } from '../users/users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly userService: UsersService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWTKEY,
});
}
async validate(payload: any) {
// check if user in the token actually exist
const user = await this.userService.findOneById(payload.id);
if (!user) {
throw new UnauthorizedException('You are not authorized to perform the operation');
}
return payload;
}
}
auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { JwtModule } from '@nestjs/jwt';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from '../users/users.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
PassportModule,
UsersModule,
JwtModule.register({
secret: process.env.JWTKEY,
signOptions: { expiresIn: process.env.TOKEN_EXPIRATION },
}),
],
providers: [
AuthService,
LocalStrategy,
JwtStrategy
],
controllers: [AuthController],
})
export class AuthModule { }
local.strategy.ts
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
secretOrKey: process.env.JWTKEY,
});
}
async validate(username: string, password: string): Promise<any>{
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException('Invalid user credentials');
}
return user;
}
}
.env file
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASS=2208
DB_DIALECT=postgres
DB_NAME_TEST=Blog
DB_NAME_DEVELOPMENT=Blog
DB_NAME_PRODUCTION=Blog
JWTKEY=32190381209831029
TOKEN_EXPIRATION=48h
BEARER=Bearer
aqex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.