0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NestJSでJWT認証が動くトリガーとタイミング

Posted at

このあたりの理解があいまいだったので、claudeに聞いて、
NestJSのJWT認証で6段階の処理が開始されるトリガーについて整理してみました。

認証処理のトリガー

メイントリガー:@UseGuards(JwtAuthGuard)

@Controller('api')
export class ProfileController {
  
  @UseGuards(JwtAuthGuard)  // ← これがトリガー
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}

このデコレータが6段階処理の開始スイッチです。

トリガーが発動するタイミング

1. リクエスト受信時

GET /api/profile
Authorization: Bearer eyJhbGciOiJIUzI1...

2. NestJSの処理順序

HTTPリクエスト受信
    ↓
ルーティング解決(/api/profile → ProfileController.getProfile)
    ↓
ガードの確認(@UseGuards(JwtAuthGuard) があるか?)
    ↓
Yes → JWT認証の6段階処理開始  ← ここがトリガーポイント
    ↓
認証成功 → コントローラーメソッド実行

トリガーの仕組み

NestJSの内部動作

// NestJSが内部で実行している疑似コード
async function handleRequest(request, route) {
  
  // 1. ルート情報からガードを確認
  const guards = getGuardsFromRoute(route);  // [@UseGuards(JwtAuthGuard)]
  
  // 2. ガードが存在する場合
  if (guards.length > 0) {
    
    // 3. 各ガードを順番に実行
    for (const guard of guards) {
      const canActivate = await guard.canActivate(request);  // ← ここで6段階開始
      
      if (!canActivate) {
        throw new UnauthorizedException();  // 認証失敗
      }
    }
  }
  
  // 4. 全ガードが成功 → コントローラー実行
  return await controller.method(request);
}

ガードの種類とトリガー

1. メソッドレベル(最も一般的)

@Get('profile')
@UseGuards(JwtAuthGuard)  // ← このメソッドのみ認証必要
getProfile() {
  return 'protected';
}

@Get('public')  // ← 認証不要
getPublic() {
  return 'anyone can access';
}

2. クラスレベル

@Controller('admin')
@UseGuards(JwtAuthGuard)  // ← このコントローラー全体が認証必要
export class AdminController {
  
  @Get('users')  // 認証必要
  getUsers() {}
  
  @Get('settings')  // 認証必要
  getSettings() {}
}

3. グローバルレベル

// main.ts
app.useGlobalGuards(new JwtAuthGuard());  // ← 全エンドポイントで認証必要

// または app.module.ts
@Module({
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,  // ← 全エンドポイントで認証必要
    },
  ],
})
export class AppModule {}

トリガーが発動しないケース

1. ガードがない場合

@Get('public')  // ← @UseGuards なし
getPublic() {
  return 'no authentication needed';  // 6段階処理は実行されない
}

2. 別のガードを使用

@Get('admin')
@UseGuards(RolesGuard)  // ← JWT以外のガード
getAdmin() {
  return 'different guard';  // JWTの6段階処理は実行されない
}

複数ガードの場合

順番に実行される

@Get('super-protected')
@UseGuards(JwtAuthGuard, RolesGuard, PremiumGuard)
getSuperProtected() {
  return 'triple protection';
}

実行順序:

1. JwtAuthGuard実行(JWT認証の6段階)
2. RolesGuard実行(ロール確認)
3. PremiumGuard実行(プレミアム確認)
4. 全て成功 → コントローラー実行

実際の動作確認

デバッグ用のカスタムガード

@Injectable()
export class DebugJwtAuthGuard extends JwtAuthGuard {
  
  async canActivate(context: ExecutionContext): Promise<boolean> {
    console.log('🔐 JWT認証開始 - 6段階処理スタート');
    
    try {
      const result = await super.canActivate(context);
      console.log('✅ JWT認証成功 - コントローラーへ');
      return result;
    } catch (error) {
      console.log('❌ JWT認証失敗 - 401エラー');
      throw error;
    }
  }
}

使用例

@Get('profile')
@UseGuards(DebugJwtAuthGuard)  // ← デバッグ用ガード
getProfile() {
  console.log('🎯 コントローラー実行中');
  return 'success';
}

コンソール出力

🔐 JWT認証開始 - 6段階処理スタート
✅ JWT認証成功 - コントローラーへ
🎯 コントローラー実行中

トリガーのタイミング図

HTTP Request
    ↓
NestJS Router
    ↓
Route Handler Discovery
    ↓
Guard Detection (@UseGuards found?)
    ↓ YES
Trigger: canActivate() method called
    ↓
【6段階のJWT認証処理開始】
1. JwtAuthGuard
2. JwtStrategy
3. JWT検証
4. ユーザー情報取得
5. Validation完了
6. Controller実行許可
    ↓
Controller Method Execution
    ↓
Response

まとめ

JWT認証の6段階処理のトリガー:

  1. 主要トリガー: @UseGuards(JwtAuthGuard)デコレータ
  2. 発動タイミング: HTTPリクエスト受信後、コントローラー実行前
  3. 内部メカニズム: NestJSがガードのcanActivate()メソッドを呼び出し
  4. スコープ: メソッド、クラス、グローバルレベルで設定可能

このトリガーシステムにより、開発者は@UseGuards()を書くだけで複雑な認証処理を自動実行できます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?