Kartu bebas CORS Access-Control-Allow-Headers diabaikan?

119

Saya kesulitan mendapatkan permintaan CORS lintas domain untuk bekerja dengan benar menggunakan Chrome.

Minta Header:

Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4

Header respons:

Access-Control-Allow-Headers:*
Access-Control-Allow-Origin:*
Allow:GET, POST, OPTIONS
Content-Length:0
Date:Tue, 30 Oct 2012 20:04:28 GMT
Server:BaseHTTP/0.3 Python/2.7.3

Kesalahan:

XMLHttpRequest cannot load domain. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

Dan kode python yang melayani permintaan opsi adalah:

self.send_response(200)
self.send_header('Allow', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Headers', '*')
self.send_header('Content-Length', '0')
self.end_headers()

Sepertinya karakter Access-Control-Allow-Originpengganti sedang diabaikan?

Ben Reeves
sumber

Jawaban:

186

Dukungan untuk karakter pengganti di Access-Control-Allow-Headerstajuk ditambahkan ke standar hidup hanya pada Mei 2016, jadi mungkin tidak didukung oleh semua browser. Pada browser yang belum menerapkan ini, ini harus sama persis: https://www.w3.org/TR/2014/REC-cors-20140116/#access-control-allow-headers-response-header

Jika Anda mengharapkan sejumlah besar header, Anda dapat membaca nilai Access-Control-Request-Headersheader dan menggemakan nilai itu kembali di Access-Control-Allow-Headersheader.

monsur
sumber
55
resp.setHeader ("Access-Control-Allow-Headers", req.getHeader ("Access-Control-Request-Headers")); // izinkan tajuk apa pun
Sam Barnum
3
Pada ruby, "jika request.headers ['Access-Control-Request-Headers'] lalu header ['Access-Control-Allow-Headers'] = request.headers ['Access-Control-Request-Headers'] end" terlihat oke buat saya
Tsuneo Yoshioka
1
@monsur: jawaban ini menunjukkan bahwa wildcard diizinkan sekarang, setidaknya dalam teori, jadi saya memperbarui jawaban Anda untuk mencerminkan ini. Jika Anda tidak menyukai gaya saya, silakan edit sesuai selera Anda.
MvG
2
Sebuah kata peringatan, Anda mungkin mengalami masalah dengan mengandalkan kembali nilai Access-Control-Request-Headers jika Anda juga mengizinkan browser untuk menyimpan cache respons preflight (dengan Access-Control-Max-Age). Anda tidak tahu bahwa permintaan pertama mencantumkan semua header permintaan yang berurutan.
Simon Ejsing
2
@monokrome akan sangat bagus jika Anda dapat memberi tahu kami bagaimana hal ini akan menjadi masalah keamanan dalam produksi ..
prettyvoid
53

Header CORS tersebut tidak mendukung *sebagai nilai, satu-satunya cara adalah menggantinya *dengan ini:

Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With


.htaccess Contoh (Termasuk CORS):

<IfModule mod_headers.c>
  Header unset Connection
  Header unset Time-Zone
  Header unset Keep-Alive
  Header unset Access-Control-Allow-Origin
  Header unset Access-Control-Allow-Headers
  Header unset Access-Control-Expose-Headers
  Header unset Access-Control-Allow-Methods
  Header unset Access-Control-Allow-Credentials

  Header set   Connection                         keep-alive
  Header set   Time-Zone                          "Asia/Jerusalem"
  Header set   Keep-Alive                         timeout=100,max=500
  Header set   Access-Control-Allow-Origin        "*"
  Header set   Access-Control-Allow-Headers       "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Expose-Headers      "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With"
  Header set   Access-Control-Allow-Methods       "CONNECT, DEBUG, DELETE, DONE, GET, HEAD, HTTP, HTTP/0.9, HTTP/1.0, HTTP/1.1, HTTP/2, OPTIONS, ORIGIN, ORIGINS, PATCH, POST, PUT, QUIC, REST, SESSION, SHOULD, SPDY, TRACE, TRACK"
  Header set   Access-Control-Allow-Credentials   "true"

  Header set DNT "0"
  Header set Accept-Ranges "bytes"
  Header set Vary "Accept-Encoding"
  Header set X-UA-Compatible "IE=edge,chrome=1"
  Header set X-Frame-Options "SAMEORIGIN"
  Header set X-Content-Type-Options "nosniff"
  Header set X-Xss-Protection "1; mode=block"
</IfModule>

FAQ:

  • Mengapa Access-Control-Allow-Headers, Access-Control-Expose-Headers, Access-Control-Allow-Methodsnilai-nilai yang super panjang?

    Mereka tidak mendukung *sintaks, jadi saya telah mengumpulkan tajuk yang paling umum (dan eksotis) dari seluruh web, dalam berbagai format # 1 # 2 # 3 (dan saya akan memperbarui daftar dari waktu ke waktu)

  • Mengapa Anda menggunakan Header unset ______sintaks?

    Server GoDaddy (tempat situs web saya dihosting ..) memiliki bug aneh di mana jika tajuk sudah disetel, nilai sebelumnya akan bergabung dengan yang sudah ada .. (bukan menggantikannya) dengan cara ini saya "membersihkan" nilai yang ada (benar-benar hanya solusi cepat && kotor )

  • Apakah aman bagi saya untuk menggunakan 'apa adanya'?

    Yah .. sebagian besar jawabannya adalah YA karena .htaccessmembatasi header ke skrip (PHP, HTML, ...) dan sumber daya (.JPG, .JS, .CSS) disajikan dari "folder" -lokasi berikut. Anda secara opsional mungkin ingin menghapus Access-Control-Allow-Methodsgaris. Juga Connection, Time-Zone, Keep-Alivedan DNT, Accept-Ranges, Vary, X-UA-Compatible, X-Frame-Options, X-Content-Type-Optionsdan X-Xss-Protectionhanya saran saya menggunakan untuk saya secara online-layanan .. merasa bebas untuk menghapus mereka juga ...

diambil dari komentar saya di atas

Komunitas
sumber
Ini pasti menyelamatkan hidup saya. Saya menggunakan penyedia CDN, dengan CORS diaktifkan, dan juga mengizinkannya di situs web saya Access-Control-Allow-Origin "*"tetapi tidak ada yang berhasil sampai saya menggunakan ini. Bahkan penyedia CDN tidak punya jawaban untuk kami. Saya menjalankan situs web di Siteground , mungkin, sebagai GoDaddy , wajib untuk menghapus semuanya terlebih dahulu.
Ignacio Bustos
Posting yang sangat bagus, ini harus ditempatkan di bagian atas halaman ini.
CommonKnowledge
1
Dalam kasus khusus saya, saya harus menghapus dari Access-Control-Allow-Methodssemua metode ini: HTTP / 0.9, HTTP / 1.0, HTTP / 1.1, HTTP / 2
umbe1987
Apakah HTTP / 2 bahkan merupakan 'Metode' yang valid? Apakah mengupgrade dari HTTP / 1.1 ke 2 berfungsi seperti itu atau semacamnya? Jika saya melihat di sini: sookocheff.com/post/networking/how-does-http-2-work, bagian HTTP / ... seharusnya ditempatkan sebagai tempat ketiga, bukan yang pertama, tempat Metode ditempatkan.
Henk Poley
Mungkin untuk mendukung HTTP / 2.0 Anda perlu menambahkan metode 'PRI'?
Henk Poley
17

Saya menemukan bahwa Access-Control-Allow-Headers: *harus disetel HANYA untuk permintaan OPTIONS. Jika Anda mengembalikannya untuk permintaan POST maka browser membatalkan permintaan (setidaknya untuk chrome)

Kode PHP berikut berfungsi untuk saya

// Allow CORS
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');    
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); 
}   
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Headers: *");
}

Saya menemukan pertanyaan serupa dengan beberapa tanggapan yang menyesatkan:

  • Untaian server mengatakan bahwa ini adalah 2 tahun bug chrome: Access-Control-Allow-Headerstidak cocok dengan localhost. Ini salah: Saya dapat menggunakan CORS ke server lokal saya dengan Post secara normal
  • Access-Control-Allow-Headersmenerima wildcard. Itu juga salah, wildcard berfungsi untuk saya (saya hanya menguji dengan Chrome)

Ini membutuhkan waktu setengah hari untuk mencari tahu masalahnya.

Selamat membuat kode

sayuran hijau
sumber
2
Karakter pengganti ("Access-Control-Allow-Headers: *") tidak berfungsi untuk saya, di Safari 7.0.4.
Tsuneo Yoshioka
Saya menemukan bahwa pengaturan Access-Control-Allow-Headers berfungsi untuk POST di Chrome Versi 40.0.2214.111 m.
Derek Greer
3
Ini tampaknya tidak benar ..... spec tidak memungkinkan *pada Access-Control-Allow-Headersbahkan untuk OPTIONS.
Pacerier
1

Dikutip dari monsur,

Header Access-Control-Allow-Headers tidak mengizinkan karakter pengganti. Ini harus sama persis: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header .

Jadi inilah solusi php saya.

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
  $headers=getallheaders();
  @$ACRH=$headers["Access-Control-Request-Headers"];
  header("Access-Control-Allow-Headers: $ACRH");
}
Jason Chiang
sumber
1
Sebenarnya, mengapa tidak begitu sajaheader('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_ALLOW_HEADERS']);
Pacerier
0

inilah mantra untuk nginx, di dalam a

location / {
    # Simple requests
    if ($request_method ~* "(GET|POST)") {
      add_header "Access-Control-Allow-Origin"  *;
    }

    # Preflighted requests
    if ($request_method = OPTIONS ) {
      add_header "Access-Control-Allow-Origin"  *;
      add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
    }

}
dcsan.dll
sumber