tech.junha.kr

Helmet의 contentSecurityPolicy 때문에 외부 스크립트가 막힐 때

오류1. 카카오 SDK 스크립트 파일 import 실패

오류2. 구글 애드센스 스크립트 파일 import 실패

Refused to load the script 'https://developers.kakao.com/sdk/js/kakao.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. result:1 Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

이유: XSS공격을 막기 위해 외부 javascript파일 import를 막아놓은 보안 기능

해결 과정

  1. HTML에 외부 스크립트 허용 메타태그 추가

  2. 웹팩 모듈 external 추가

  3. 웹 팩 엔트리에 외부 스크립트 주소 입력

  4. sdk를 직접 다운 받아, 로컬환경에서 웹팩으로 번들링 --> 애드센스 스크립트는 불가

  5. helmet CSP설정 수정

css, image들은 문제없이 import되었떤 이유는 helmetCSP에 JS만 막아놓았기 때문이다.

이때 스크립트를 지웠다 없애고 다시 추가해야 컨솔에 오류가 사라진다.

app.use(
  helmet({
    contentSecurityPolicy: false,
  })
);

const contentSecurityPolicy = require("helmet-csp");

app.use(
  contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'", "default.example"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [],
    },
    reportOnly: false,
  })
);

github.com/helmetjs/helmet/tree/main/middlewares/content-security-policy

helmetjs/helmet

blog.uniony.me/nodejs/helmet/

Express 웹사이트 보안 강화하기 [Helmet, CSP]

crispypotato.tistory.com/72

helmet, helmet-csp사용방법, 오류 Refused to load the