问题
There is something about Cross Origin Resource Sharing (CORS) that I have never truly understood, namely that with a cross-origin HTTP request, it is not the client that gets to decide which server(s) it wants to trust; instead, the server declares (in the Access-Control-Allow-Origin
response header) that one or more particular clients (origins) trust it. A CORS-enabled browser will only deliver the server's response to the application if the server says that the client trusts the server. This seems like a reverse way of establishing a trust relationship between two HTTP parties.
What would make more sense to me is a mechanism similar to the following: The client declares a list of origins that it trusts; for example, via some fictional <meta allow-cross-origin="https://another-site:1234"/>
element in the <head>
. (Of course a browser would have to ensure that these elements are read-only and cannot be removed, modified, or augmented via scripts.)
What am I misunderstanding about CORS? Why would a client-side declaration of trusted origins not work? Why is it that the servers get to confirm which clients (origins) may trust its responses? Who is actually protected from whom by CORS? Does it protect the server, or the client?
(These are a lot of questions. I hope it's clear that I am not expecting an answer to each of these, but rather just an answer that points out my fundamental misunderstanding.)
回答1:
Client has nothing to do with it. With a CORS header you're telling the client which other servers do I trust. Those then can share your resources and client wont mind.
For example if you have two domains you tell the client so let your resources be used by your second website, you dont say i trust you as a client.
So you're protecting the server, not client. You dont want AJAX API Endpoints to be accessible by scripts hosted anywhere in the world.
A client has nothing to gain/lose from this. Its only a protection for servers because using AJAX all the URLs are clearly visible to anyone and had it been not for this protection, anybody could go ahead run their front end using your API, only servers have to lose from this so they get to decide who can use their resources.
来源:https://stackoverflow.com/questions/39246541/with-cors-why-do-servers-declare-which-clients-may-trust-it-instead-of-clients