ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • nodejs 외부 모듈 인증창 띄우기 - CSP 설정 - helmet
    NULL STACK 2023. 7. 11. 18:42
    반응형

    CSP는 Content Security Policy(콘텐츠 보안 정책)의 약자입니다. 
    이는 웹사이트 보안을 강화하는 데 사용되며, 기본적으로 웹사이트에서 로드되는 리소스(이미지, 폰트, 스크립트 등)들의 출처를 명시하고, 웹사이트에 포함된 스크립트 실행을 제한하는 기능을 제공합니다. 
    이를 통해 사이버 공격 유형 중 하나인 XSS(Cross-Site Scripting) 공격을 방지할 수 있습니다.


    외부 모듈(예를 들면 nice 인증)과 통신하여 해당 모듈을 열어야 할 때,
    백엔드에서 강제로 submit하는 스크립트를 실행시켜주는 모듈을 렌더링 시켜 줄 수도 있겠다

    이때 주의해야 할 점은, 해당 렌더링 된 화면에서 스크립트를 통한 공격인데
    helmet이라는 모듈이 이를 방어해준다.

    단 외부 모듈에서 해당 스크립트를 실행시켜야 할 경우, 예외처리를 해주어야 하며 나는 nonce를 사용하여 허용된 스크립트만 실행 되도록 처리했다.

      app.use((req, res, next) => {
        res.locals.cspNonce = crypto.randomBytes(16).toString('hex');
        next();
      });
    
      app.use(
        helmet({
          contentSecurityPolicy: {
            directives: {
              scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
              formAction: ["'self'", 'https://foo-bar-url'],
            },
          },
        })
      );
    }

    위 코드처럼 미들웨어에서 nonce를 발행 한 후, 렌더링 되어야 하는 코드의 스크립트에서 nonce로 넣어준다.

     

    관련 에러:

    더보기

    Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash, or a nonce ('nonce-...') is required to enable inline execution.

     

    Refused to send form data to 'https://foo-bar-url' because it violates the following Content Security Policy directive: "form-action 'self'".

     

    반응형
Designed by Tistory.