LoginSignup
0
0

More than 1 year has passed since last update.

[Firebase + NestJS] jsonwebtokenがいきなりタテついてきた件

Last updated at Posted at 2022-01-19

あらすじ

いつものように開発していたが、突如github actionが落ちた・・・
何事かと中身を見ると下記エラーが発生していた。

src/auth/firebase.guard.ts:57:22 - error TS2339: Property 'email_verified' does not exist on type 'string | JwtPayload'.
  Property 'email_verified' does not exist on type 'string'.

57         if (!decoded.email_verified)

む!?

ちなみに該当コードの前後はこんな感じ
firebaseの認証を使っていて、jsonwebtokenというパッケージを使って
jwtを公開鍵で検証したあと取り出したデータの中身を検証する場所だった。

jwt.verify(jwtToken, cert, { algorithms: ['RS256'] }, (err, decoded) => {
  if (err) throw new BadGatewayException(err);

  if (!decoded.email_verified)
    throw new BadGatewayException(
      'Auth Error: メール認証がされていません',
    );

解決法

エラーの内容を見るに、

stringまたはJwtPayloadらしいけど、
stringだったらemail_verifiedなんてプロパティねぇぞ!

って意味です。

ですので、string型である可能性を潰してあげましょう

jwt.verify(jwtToken, cert, { algorithms: ['RS256'] }, (err, decoded) => {
  if (err) throw new BadGatewayException(err);

  // ここから
  if (typeof decoded === 'string')
    throw new BadGatewayException('認証エラー__jwtデコード失敗');
  // ここまで

  if (!decoded.email_verified)
    throw new BadGatewayException(
      'Auth Error: メール認証がされていません',
    );

あとがき

コードの変更ほとんどしていないのに、急にビルド通らなくなるから焦りました。
同じところでハマってる方のヘルプになれば幸いです。
ちなみにどういう時stringの型としてデータが入るかまでは検証していません。
詳しい方いたら教えてください。

補足

JwtPayloadの本来のお姿はこっちでした。

export type VerifyCallback<T = JwtPayload> = (
    err: VerifyErrors | null,
    decoded: T | undefined,
) => void;
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0