admin管理员组

文章数量:1406002

I'm having an error where after the user logs in, I create an access token and a refresh token, the access token works, and is practically the same as the refresh, it doesn't give an invalid: signature error, but refresh gives this error, even though the secret and signature are the same, does anyone know what's happening, a more internal error?

my config for both token and refresh token:

JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get<string>('access_secret_jwt_token'),
        signOptions: {
          expiresIn: configService.get<string>('acess_jwt_token_expiration'),
        },
      }),
    }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get<string>('access_refresh_secret'), 
        signOptions: {
          expiresIn: configService.get<string>('refresh_jwt_token_expiration'),
        },
      }),

they both right, the secret is right, nothing wrong.

this async function generates a new acess token with refresh token:

@UseGuards(RefreshTokenAutenticacaoGuard)
  @Mutation(() => MessageDataTokenRefreshResponse)
  async refreshGenerarateToken(@Context() req: any) {
    console.log('Dados do context req refresh');
    const ep1 = req.user.sub;
    const ep2 = req.user.email;
    const ep3 = req.user.type_token;
    console.log('Dados do Refresh Token rapai: ', ep1, ep2, ep3);
    return await this.usuariosService.refreshGeneratesToken(
      req.user.sub,
      req.user.email,
      req.user.type_token,
    );
  }

now its the refresh strategy:

@Injectable()
export class RefreshJwtStrategy extends PassportStrategy(Strategy, 'refresh') {
  constructor(
    private ConfigService: ConfigService,
    private usuarioService: UsuarioService,
    private readonly jwtService: JwtService,
  ) {
    super({
      jwtFromRequest: (req) => {
        const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
        console.log('Token extraído:', token);
        const dataToken = jwtService.decode(token, { complete: true });
        console.log('Data do token :', dataToken);
        const teste = jwtService.verify(token, {
          secret:
            '6fde91ad8df1b91965b81f66c8fd6b347dc741841b4b38502fd9e0d7837a713c',
        });
        console.log('teste do signature refresh: ', teste);
        // const respostaData = jwtService.verify(token, {
        //   secret: ConfigService.get<string>('refresh_secret'),
        // });
        // console.log('Resposta do data token :', respostaData);
        return token;
      },
      secretOrKey: ConfigService.get<string>('access_refresh_secret'),
      ignoreExpiration: false,
      passReqToCallback: true,
    });

    console.log(
      'secret do refresh: ',
      this.ConfigService.get<string>('access_refresh_secret'),
    );
  }

  async validate(req: Request, payload: AuthJwtRefreshPayload) {
    console.log('Payload recebido:', payload);
    console.log('passou aqui no validate');
    const refreshToken = req.headers.authorization.replace('Bearer', '').trim();
    const userId = payload.sub;
    const email = payload.emailUser;
    const type_token = payload.type_token;
    const data = await this.usuarioService.validateRefreshToken(
      userId,
      email,
      type_token,
      refreshToken,
    );
    return {
      sub: data.idUsuario,
      email: data.email,
      type_token: data.type_token,
    };
  }
}

the refresh guard, same as token guard, but the authGuard string is different so as not to confuse the passport.

@Injectable()
export class RefreshTokenAutenticacaoGuard extends AuthGuard('refresh') {
  getRequest(context: ExecutionContext) {
    console.log('passou aqui');
    const ctx = GqlExecutionContext.create(context);
    const req = ctx.getContext().req;
    console.log('Request no Guard:', req.headers.authorization);
    return req;
  }
}

now the error:

[Nest] 42  - 03/06/2025, 1:33:31 AM   ERROR [ExceptionsHandler] JsonWebTokenError: invalid signature                                              
fineon-1          |     at /usr/src/app/node_modules/jsonwebtoken/verify.js:171:19                                                                                    
fineon-1          |     at getSecret (/usr/src/app/node_modules/jsonwebtoken/verify.js:97:14)
fineon-1          |     at module.exports [as verify] (/usr/src/app/node_modules/jsonwebtoken/verify.js:101:10)                                                       
fineon-1          |     at JwtService.verify (/usr/src/app/node_modules/@nestjs/jwt/dist/jwt.service.js:67:20)                                                        
fineon-1          |     at RefreshJwtStrategy.jwtFromRequest [as _jwtFromRequest] (/usr/src/app/dist/apps/fineon/main.js:3308:42)
fineon-1          |     at JwtStrategy.authenticate (/usr/src/app/node_modules/passport-jwt/lib/strategy.js:93:22)                                                    
fineon-1          |     at attempt (/usr/src/app/node_modules/passport/lib/middleware/authenticate.js:378:16)                                                         
fineon-1          |     at authenticate (/usr/src/app/node_modules/passport/lib/middleware/authenticate.js:379:7)
fineon-1          |     at /usr/src/app/node_modules/@nestjs/passport/dist/auth.guard.js:88:3                                                                         
fineon-1          |     at new Promise (<anonymous>)   

this gives a error saying that the jwt signature is invalid, but how? I have already checked the refresh token, it was generated with the same secret, both the token and the refresh token, and the strategy token is the same as the refresh strategy, but it does not give an error, but the refresh strategy gives this error, why? Did I implement it in some wrong way? If you need any more information to try to solve it, you can tell me in the chat.

obs: the secret is a openssl size 32.

obs: both token acess and refresh openssl strings are diferent, not the same.

本文标签: typescriptJwt gives error for invalid signaturebut is not invalidStack Overflow