Security implications of adding all domains to CORS (Access-Control-Allow-Origin: *)

后端 未结 6 904
深忆病人
深忆病人 2020-12-07 22:51

It is said that instead of adding all domains to CORS, one should only add a set of domains. Yet it is sometimes not trivial to add a set of domains. E.g. if I want to publi

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 23:07

    You can send more than one, like:

    Access-Control-Allow-Origin: http://my.domain.com https://my.domain.com http://my.otherdomain.com
    

    but I would advise against it. Instead, keep a whitelist of allowed domains. Lets say:

    allowed = [ "X", "Y", "A.Z" ];
    

    Then if you get a request from X you respond with:

    Access-Control-Allow-Origin: X
    

    If you get a request from A.Z you respond with:

    Access-Control-Allow-Origin: A.Z
    

    If you get a request from a domain that is not allowed, respond with an error or no CORS policy.

    All XHR requests will send an Origin header, so use that. And you only need to send the CORS policy headers for the OPTIONS request, not the GET/POST/HEAD request that follows.


    The main issue I see is that you expose all your domains. Maybe you have a secure admin domain like: https://admin.mydomain.com, or maybe you have a product website that isn't ready for launch yet. You don't want to include anything that isn't absolutely necessary for the request at hand.

    And * is just extremely lazy.


提交回复
热议问题