학습

Python cors

Grower 2022. 8. 20. 17:08

django-cors-headers 3.13.0

Released: Jun 6, 2022

 

# 설치

python -m pip install django-cors-headers

 

# INSTALLED_APPS

and then add it to your installed apps:

번역:

settings.py 에서 INSTALLED_APPS 에 corsheaders 를 추가합니다.

INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

# MIDDLEWARE

Make sure you add the trailing comma or you might get a ModuleNotFoundError (see this blog post).
You will also need to add a middleware class to listen in on responses:

번역:

후행 쉼표를 추가해야 합니다. 그렇지 않으면 ModuleNotFound 오류가 발생할 수 있습니다.
또한 응답을 수신하려면 미들웨어 클래스를 추가해야 합니다.

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

CorsMiddleware should be placed as high as possible, especially before any middleware that can generate responses such as Django’s CommonMiddleware or Whitenoise’s WhiteNoiseMiddleware. If it is not before, it will not be able to add the CORS headers to these responses.

Also if you are using CORS_REPLACE_HTTPS_REFERER it should be placed before Django’s CsrfViewMiddleware (see more below).

번역:

CORS미들웨어는 특히 Django의 커먼 미들웨어나 화이트노이즈의 화이트노이즈 미들웨어와 같은 응답을 생성할 수 있는 미들웨어보다 높은 위치에 배치되어야 한다. 이전 버전이 아니면 이 응답에 CORS 헤더를 추가할 수 없습니다.

또한 CORS_REPLACE_HTTPS_REFERER를 사용하는 경우 Django의 CsrfView 미들웨어 앞에 배치해야 합니다(아래 참조).

 

Configuration

Configure the middleware’s behaviour in your Django settings. You must set at least one of three following settings:

 

번역:

Django 설정에서 미들웨어의 동작을 구성합니다. 다음 세 가지 설정 중 하나 이상을 설정해야 합니다.

  • CORS_ALLOWED_ORIGINS
  • CORS_ALLOWED_ORIGIN_REGEXES
  • CORS_ALLOW_ALL_ORIGINS

 

# CORS_ALLOWED_ORIGINS

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "https://sub.example.com",
    "http://localhost:8080",
    "http://127.0.0.1:9000",
]

A list of origins that are authorized to make cross-site HTTP requests. The origins in this setting will be allowed, and the requesting origin will be echoed back to the client in the Access-Control-Allow-Origin header. Defaults to [].

 

An Origin is defined by the CORS RFC Section 3.2 as a URI scheme + hostname + port, or one of the special values 'null' or 'file://'. Default ports (HTTPS = 443, HTTP = 80) are optional.

The special value null is sent by the browser in “privacy-sensitive contexts”, such as when the client is running from a file:// domain. The special value file:// is sent accidentally by some versions of Chrome on Android as per this bug.

 

번역:

교차 사이트 HTTP 요청을 만들 수 있는 권한이 있는 원본 목록입니다. 이 설정의 출처가 허용되고 요청 출처는 Access-Control-Allow-Origin 헤더에서 클라이언트에 다시 에코됩니다. 기본값은 []입니다.


오리진은 CORS RFC 섹션 3.2에 의해 URI 구성표 + 호스트 이름 + 포트 또는 특수 값 'null' 또는 'file://' 중 하나로 정의됩니다. 기본 포트(HTTPS = 443, HTTP = 80)는 선택 사항입니다.

특수 값 null은 클라이언트가 파일:// 도메인에서 실행되는 경우와 같이 "개인 정보에 민감한 컨텍스트"에서 브라우저에 의해 전송됩니다. 이 버그에 따라 Android의 일부 Chrome 버전에서 특수 값 파일://이 잘못 전송되었습니다.

 

 

# CORS_ALLOWED_ORIGIN_REGEXES

CORS_ALLOWED_ORIGIN_REGEXES = [
    r"^https://\w+\.example\.com$",
]

 

A list of strings representing regexes that match Origins that are authorized to make cross-site HTTP requests. Defaults to []. Useful when CORS_ALLOWED_ORIGINS is impractical, such as when you have a large number of subdomains.

 

번역:

교차 사이트 HTTP 요청을 만들 수 있는 Origins와 일치하는 정규식을 나타내는 문자열 목록입니다. 기본값은 []입니다. 많은 수의 하위 도메인이 있는 경우와 같이 CORS_ALLOWED_ORIGINS가 실용적이지 않을 때 유용합니다.

 

 

# CORS_ALLOW_ALL_ORIGINS

CORS_ALLOW_ALL_ORIGINS = True

If True, all origins will be allowed. Other settings restricting allowed origins will be ignored. Defaults to False.

 

Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours. Generally you’ll want to restrict the list of allowed origins with CORS_ALLOWED_ORIGINS or CORS_ALLOWED_ORIGIN_REGEXES.

Previously this setting was called CORS_ORIGIN_ALLOW_ALL, which still works as an alias, with the new name taking precedence.

 

번역:

True이면 모든 출처가 허용됩니다. 허용된 출처를 제한하는 다른 설정은 무시됩니다. 기본값은 False입니다.

 

이 값을 True으로 설정하면 웹 사이트에서 사용자에게 교차 출처를 요청할 수 있으므로 위험할 수 있습니다. 일반적으로 CORS_ALLOWED_ORIGINS 또는 CORS_ALLOWED_ORIGEXS를 사용하여 허용된 오리진 목록을 제한하려고 합니다.

이전에 이 설정은 CORS_ORIGIN_ALLLOW_ALL로 불렸으며 여전히 별칭으로 작동하며 새 이름이 우선합니다.

 

 

# 참고자료

https://pypi.org/project/django-cors-headers/

 

django-cors-headers

django-cors-headers is a Django application for handling the server headers required for Cross-Origin Resource Sharing (CORS).

pypi.org

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

 

Cross-Origin Resource Sharing (CORS) - HTTP | MDN

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which

developer.mozilla.org

https://evan-moon.github.io/2020/05/21/about-cors/

 

CORS는 왜 이렇게 우리를 힘들게 하는걸까?

이번 포스팅에서는 웹 개발자라면 한번쯤은 얻어맞아 봤을 법한 정책에 대한 이야기를 해보려고 한다. 사실 웹 개발을 하다보면 CORS 정책 위반으로 인해 에러가 발생하는 상황은 굉장히 흔해서

evan-moon.github.io