fix(auth): centralize JWT secret with registerAsync to ensure consistent signing and verification
This commit is contained in:
1 parent
1a21c4c642
commit
0c32985ce2
3 files changed
+22
-14
No files matched your search
@@ -0,0 +1,14 @@
|
||||
export const DEFAULT_JWT_SECRET =
|
||||
'canina_jwt_fallback_access_secret_32_characters_minimum_len_2026';
|
||||
|
||||
export const DEFAULT_JWT_REFRESH_SECRET =
|
||||
'canina_jwt_fallback_refresh_secret_32_characters_minimum_len_2026';
|
||||
|
||||
export const getJwtSecret = (): string =>
|
||||
process.env.JWT_ACCESS_SECRET ||
|
||||
process.env.JWT_SECRET ||
|
||||
DEFAULT_JWT_SECRET;
|
||||
|
||||
export const getJwtRefreshSecret = (): string =>
|
||||
process.env.JWT_REFRESH_SECRET ||
|
||||
DEFAULT_JWT_REFRESH_SECRET;
|
||||
@@ -5,19 +5,17 @@ import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { JwtStrategy } from './jwt.strategy';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
|
||||
const JWT_SECRET =
|
||||
process.env.JWT_ACCESS_SECRET ||
|
||||
process.env.JWT_SECRET ||
|
||||
'canina_jwt_fallback_secret_32_characters_minimum_len_2026';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
PassportModule,
|
||||
JwtModule.register({
|
||||
secret: JWT_SECRET,
|
||||
signOptions: { expiresIn: '7d' },
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
secret: getJwtSecret(),
|
||||
signOptions: { expiresIn: '7d' },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ExtractJwt, Strategy } from 'passport-jwt';
|
||||
import { PassportStrategy } from '@nestjs/passport';
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
@@ -13,15 +14,10 @@ export interface JwtPayload {
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private readonly usersService: UsersService) {
|
||||
const secret =
|
||||
process.env.JWT_ACCESS_SECRET ||
|
||||
process.env.JWT_SECRET ||
|
||||
'canina_jwt_fallback_secret_32_characters_minimum_len_2026';
|
||||
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: secret,
|
||||
secretOrKey: getJwtSecret(),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user