CORS(교차 출처 리소스 공유) 설정하기

:notebook_with_decorative_cover: This is a how-to guide that will guide you through the process of setting up Cross-Origin Resource Sharing (CORS) in Discourse.

CORS is a mechanism that allows many resources (e.g., fonts, JavaScript, etc.) on a web page to be requested from another domain outside the domain from which the resource originated.

Here’s how you can set up CORS on your Discourse site:

Prerequisites

Before getting started, the DISCOURSE_ENABLE_CORS environmental variable must be set to true to enable CORS.

For assistance with this, see How to Set Environmental Variables.

:sparkles: If you are on a Discourse hosted site, this step has already been done, and you do not need to take any additional action to configure this.

Access Site Settings

Go to your Discourse admin panel. From there, navigate to the “Settings” tab.

Locate CORS Settings

In the “Settings” tab, use the search bar and type in cors origin. You should see the following setting related to CORS:

This setting allows you to specify the domains that are allowed to make cross-origin requests to your Discourse instance.

You should enter the exact domains here, separated by a space. Avoid using a wildcard (*) as this can pose security risks.

When adding multiple domains here, each URL should be separated. For example:

Save Changes

After you’ve made the necessary changes, don’t forget to click the Save Changes button at the bottom of the page.

Important Notes

Improper implementation of CORS (Cross-Origin Resource Sharing) can introduce potential security risks. Here are a few things to keep in mind when enabling CORS on your site:

  • Specify exact domains: Using wildcards (*) in the CORS configuration can allow any domain to interact with your server, which is a significant security risk. It’s recommended to specify exact domains.
  • Minimize exposed data: CORS should be set up to expose only the necessary data from external domains that you trust. Allowing sites you do not control CORS access is not recommended.
  • Use HTTPS: When possible, avoid allowing non-HTTPS sites in your CORS configuration, as this can expose data in an unencrypted format.

Last edited by @hugh 2024-05-29T06:25:46Z

Check documentPerform check on document:
2개의 좋아요

And if Google ads are in use perhaps it is better to keep hands off from this setting :wink:

CORS (and CSP) is a bit problematic because quite often a site must allow de facto everything and then it is close to useless.

2개의 좋아요

사이트의 app.yml 파일 env 섹션에 DISCOURSE_ENABLE_CORS: "true"를 추가했습니다.
그 후 앱을 다시 빌드했습니다.
이어서 cors_origins 섹션으로 가서 상호작용을 시도하는 사이트의 전체 URL을 추가했지만 여전히 작동하지 않습니다.
메인 사이트가 오프라인일 때 정보를 제공하기 위한 페이지를 생성했습니다.
이 페이지에 메인 사이트 상태를 확인하고, 복구되면 해당 사이트로 리다이렉트하기 위한 다음 JS를 넣었지만 작동하지 않는 것 같습니다.
코드는 다음과 같습니다:

    <script>
        function checkSiteStatus() {
            fetch('https://discourse.technospider.com', {
                method: 'HEAD',
                mode: 'cors', // Use CORS to get status code
                cache: 'no-store' // Avoid caching
            })
            .then(response => {
                console.log('Site check: Status', response.status);
                if (response.ok) { // 200-299 status codes
                    console.log('Site is up, redirecting to Discourse');
                    window.location.replace('https://discourse.technospider.com');
                } else {
                    console.log('Site is still down (status: ' + response.status + '), retrying in 20 seconds');
                    setTimeout(checkSiteStatus, 20000);
                }
            })
            .catch(error => {
                console.log('Site check: Error (likely down or CORS issue):', error.message);
                setTimeout(checkSiteStatus, 20000);
            });
        }
            
        // Start checking immediately
        checkSiteStatus();
    </script>

그리고 콘솔 오류는 다음과 같습니다:

[Error] Origin https://www.technospider.com is not allowed by Access-Control-Allow-Origin. Status code: 200
[Error] Fetch API cannot load https://discourse.technospider.com/ due to access control checks.
[Error] Failed to load resource: Origin https://www.technospider.com is not allowed by Access-Control-Allow-Origin. Status code: 200 (discourse.technospider.com, line 0)
[Log] Site check: Error (likely down or CORS issue): – "Load failed" (berightback, line 78)
```\n혹시 통찰이 있으신 분이 계시다면 알려주시면 좋겠습니다. Grok과 저는 막막합니다.

이중 따옴표를 제거하고 시도해 보세요. 그렇지 않으면 불리언 값이 아닌 문자열로 해석될 수 있습니다.

지금 재구성이 완료될 때까지 기다리며 테스트하고 있습니다. 만약 그게 사실이라면, 누군가가 이 페이지를 수정해야 합니다:

이 페이지에는 true를 이중 인용부호 안에 넣도록 안내하고 있기 때문입니다.

재구성 완료, 변경 사항 없음. :frowning:

글쎄, 그건 좀 이상하네… 다른 환경 변수들은 따옴표 없이 true 값이 들어 있거든.

예를 들어 게시글에서 JavaScript를 사용하려면 CSP보다 이 방식이 더 나은가요?

현재 저는 JavaScript를 실행하기 위해 테마 컴포넌트나 CSP에 의존하고 있습니다.

감사합니다.
올레

여기서는 환경 변수로 들어가는데, 환경 변수는 문자열만 가능합니다. 그래서 상관없습니다.

하지만 일반적으로는 이런 점을 주의할 필요가 있습니다. 무해해 보이는 값에서 의도하지 않은 결과가 나올 수 있기 때문입니다:

pry(main)> YAML.load('on: yes').to_s
=> "{true=>true}"
1개의 좋아요

안녕하세요! 제가 통제하지 않는 잠재적으로 위험한 웹사이트에서 /latest.json을 로드하고 싶습니다. /latest.json과 같은 특정 URL에 대해서만 CORS 헤더를 활성화하고, 예를 들어 /u/myname/user-menu-private-messages에는 활성화하지 않는 것이 가능한가요?