LoginSignup
0
0

csurfを使ってCSRF対策だ!

Posted at

手順

  1. 必要なパッケージのインストールする。

    $ npm install csurf cookie-parser
    
  2. ミドルウェアの設定を行う。

    main.ts
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import * as csurf from 'csurf';
    import * as cookieParser from 'cookie-parser';
    
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
    
      // CookieParserミドルウェアを追加
      app.use(cookieParser());
    
      // CSRFミドルウェアを追加
      app.use(csurf({ cookie: true }));
    
      await app.listen(3000);
    }
    
    bootstrap();
    
  3. CSRFトークンを提供するエンドポイントの作成する。

    app.controller.ts
    import { Controller, Get, Req } from '@nestjs/common';
    import { Request } from 'express';
    
    @Controller()
    export class AppController {
      @Get('csrf-token')
      getCsrfToken(@Req() request: Request): any {
        // CSRFトークンを生成してレスポンスする
        return { csrfToken: request.csrfToken() };
      }
    }
    
  4. フロントエンドでCSRFトークンを含めてリクエストを送る。
    以下のようなヘッダーを想定している。
    CSRFトークンが含まれていない場合は403エラーを返します。

headers: {
    "Content-Type": "application/json",
    "CSRF-Token": csrfToken
}

参考

NestJS CSRF対策 やり方
csurf - npm
csurf

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