How to extract token string from Bearer token? i need this method befor @UseGuards(JwtAuthGuard) in nest ? i use nextjs for front

huangapple go评论79阅读模式
英文:

How to extract token string from Bearer token? i need this method befor @UseGuards(JwtAuthGuard) in nest ? i use nextjs for front

问题

我在Nextjs中使用了fetch方法。

async function fetchProfile() {
  const res = await fetch(`http://localhost:5000/api/v1/users/1`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      "token": "Bearer " + localStorage.getItem("token")
    }
  })
}

这是我的控制器。

@UseGuards(JwtAuthGuard)
@Get(':id')
findOne(@Param('id', ParseIntPipe) params: { id: number }, @Req() req) {
  console.log(req);
  return this.userService.findOne(params.id, req);
}

如果我注释掉第一行,将会在控制台日志中看到一个带有令牌的内容。

token: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJlbWFpbCI6ImF6YWQuaG9zc2VpbjIzQGdtYWlsLmNvbSIsImlhdCI6MTY5MDA5NzE4OX0._ncc6g71l8mrmgNTUUybhPRG696tX8sE3GAL-Fs_Kzo',
英文:

I use the fetch method in Nextjs

async function fetchProfile() {
    const res = await fetch(`http://localhost:5000/api/v1/users/1`, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        "token": "Bearer " + localStorage.getItem("token")
      }
    })
}

this is my controller

@UseGuards(JwtAuthGuard)
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) params: { id: number }, @Req() req) {
    console.log(req);
    return this.userService.findOne(params.id, req);
  }

if I comment first line give the console log with a token like

token: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJlbWFpbCI6ImF6YWQuaG9zc2VpbjIzQGdtYWlsLmNvbSIsImlhdCI6MTY5MDA5NzE4OX0._ncc6g71l8mrmgNTUUybhPRG696tX8sE3GAL-Fs_Kzo',

答案1

得分: 1

你可以从你的策略中这样做:

    export class JwtAppStrategy extends PassportStrategy(Strategy, 'strategy-name') {
      constructor(private config: ConfigService, private userService: UserService) {
        super({
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // 从头部提取
          secretOrKey: 'secret',
        });
      }
    
      async validate(payload: { id: number }) {
        // 自定义逻辑
        return true;
      }
    }
英文:

You can do it from your strategy:

export class JwtAppStrategy extends PassportStrategy(Strategy, 'strategy-name') {
  constructor(private config: ConfigService, private userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // extract from header
      secretOrKey: 'secret',
    });
  }

  async validate(payload: { id: number }) {
    // custom logic
    return true;
  }
}

答案2

得分: 0

我使用这个策略,并且运行得很完美。

constructor() {
  super({
    jwtFromRequest: ExtractJwt.fromExtractors([
      JwtStrategy.extractJWT,
      ExtractJwt.fromAuthHeaderAsBearerToken(),
    ]),
    // passReqToCallback: true,
    secretOrKey: jwtSecret,
  });
}

private static extractJWT(req: Request): string | null {
  if (req.cookies && 'token' in req.headers) {    
    return JwtStrategy.extractToken(req);
  }
  return null;
}

private static extractToken(req) {
  if (req.headers.token && req.headers.token.split(' ')[0] === 'Bearer') {
    return req.headers.token.split(' ')[1];
  } else if (req.query && req.query.token) {
    return req.query.token;
  }
  return null;
}

希望这对你有所帮助。

英文:

I use this strategy and work perfectly

constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        JwtStrategy.extractJWT,
        ExtractJwt.fromAuthHeaderAsBearerToken(),
      ]),
      // passReqToCallback: true,
      secretOrKey: jwtSecret,
    });
  }

  private static extractJWT(req: Request): string | null {
    if (req.cookies && 'token' in req.headers) {    
      return JwtStrategy.extractToken(req);
    }
    return null;
  }

  private static extractToken(req) {
    if (req.headers.token && req.headers.token.split(' ')[0] === 'Bearer') {
      return req.headers.token.split(' ')[1];
    } else if (req.query && req.query.token) {
      return req.query.token;
    }
    return null;
  }

huangapple
  • 本文由 发表于 2023年7月23日 16:14:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定