SE TE COMPLICO?
DEJA TE HECHO UNA MANITA
1.- Primero creamos el archivo jwt.strategy.ts en el cual agregaremos lo siguiente
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';
import { TokenPayloadModel } from './models/token.model';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
// OBTENDREMOS EL TOKEN LOS HEADERS COMO 'Bearer token'
ignoreExpiration: false,
// IGNORA LA EXPIRACION, EN TU CASO EL TIEMPO QUE LE HAYAS PUESTO
// EJE. signOptions: { expiresIn: '24h' }, YO LE PUSE 1 DIA
secretOrKey: jwtConstants.secret,
// LA LLAVE SECRETA CON LA QUE FIRMAMOS EL TOKEN AL HACER LOGIN
});
}
// ESTA FUNCION LO QUE HARA SERA RECIBIR EL TOKEN DECODIFICADO
// CON LA CARGA DE DATOS QUE LE PUSIMOS AL HACER LOGIN
async validate( payload: TokenPayloadModel ) {
return payload;
}
}
LA FUNCION VALIDATE ES IMPORTANTE YA QUE SI EL TOKEN ES VALIDO POR NUESTRO SERVIDOR, ESTE RETURN DE LA FUNCION MISMA DEVOLVERA EL PAYLOAD AL REQUEST DE NUESTRA RUTA A LA QUE VAYAMOS A PROTEGER, ESTO TE PUEDE SERVIR PARA A BUSCAR EN TU BD AL USUARIO O ALGUN PROCESO QUE REQUIERAS
2.- Lo siguiente es importar nuestra estrategia en nuestro modulo de autenticación en los providers
"auth.module.ts"
import { JwtStrategy } from './jwt.strategy';
@Module({
imports: [
...Tus imports
],
controllers: [Tus Controllers...],
providers: [Tus demas providers..., JwtStrategy]
})
export class AuthModule {}