크롬 익스텐션 개발 중, 백그라운드 스크립트에서 인증 헤더를 포함해 api 요청을 보낼 일이 있었다.
요청에는 Authorization: Bearer {token}
을 포함하고, 응답에는 Access-Control-Allow-Origin: *
을 추가했다.
물론 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
헤더가 사라진다. 올바르지 않은 해결법.
자격 증명을 포함한 요청 전송
자격 증명을 포함한 경우 Access-Control-Allow-Origin
에 와일드 카드를 포함해서는 안된다.
그렇다면 origin
을 명시해주는게 맞는데, 개개인별로 extension-id
가 다른데 어떻게 명시를 해줘야할지 머리가 아팠다.
{
"name": "My extension",
...
"host_permissions": [
"https://{server-url}"
],
...
}
다음과 같이 매니페스트의 host_permissions
에 서버 경로를 추가해주면 된다. 여기서는 무려 와일드 카드 문자도 사용 가능하다.