[chrome-extension] background script cors 발생

bluejoy·2023년 11월 2일
0

상황

크롬 익스텐션 개발 중, 백그라운드 스크립트에서 인증 헤더를 포함해 api 요청을 보낼 일이 있었다.
요청에는 Authorization: Bearer {token}을 포함하고, 응답에는 Access-Control-Allow-Origin: *을 추가했다.

문제 1

물론 cors 에러가 발생했다.

Access to fetch at 'https://{server-url}' from origin 'chrome-extension://{extension-id}' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://{server-origin} that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

단순하게 해결하기

no-cors를 추가하면 Authorization 헤더가 사라진다. 올바르지 않은 해결법.

실질적인 문제 1

자격 증명을 포함한 요청 전송

자격 증명을 포함한 경우 Access-Control-Allow-Origin에 와일드 카드를 포함해서는 안된다.

그렇다면 origin을 명시해주는게 맞는데, 개개인별로 extension-id가 다른데 어떻게 명시를 해줘야할지 머리가 아팠다.

해결법

cross-origin network requests

{
  "name": "My extension",
  ...
  "host_permissions": [
    "https://{server-url}"
  ],
  ...
}

다음과 같이 매니페스트의 host_permissions에 서버 경로를 추가해주면 된다. 여기서는 무려 와일드 카드 문자도 사용 가능하다.

profile
개발자 지망생입니다.

0개의 댓글