How to set a cookie for another domain

后端 未结 11 1789
一向
一向 2020-11-22 07:21

Say I have a website called a.com, and when a specific page of this site is loaded, say page link, I like to set a cookie for another site called b.com

相关标签:
11条回答
  • 2020-11-22 07:48

    In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.

    0 讨论(0)
  • 2020-11-22 07:49

    Setting cookies for another domain is not possible.

    If you want to pass data to another domain, you can encode this into the url.

    a.com  ->  b.com/redirect?info=some+info (and set cookie) -> b.com/other+page
    
    0 讨论(0)
  • 2020-11-22 07:53

    You can't, but... If you own both pages then...

    1) You can send the data via query params (http://siteB.com/?key=value)

    2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)

    0 讨论(0)
  • 2020-11-22 07:55

    You can't, at least not directly. That would be a nasty security risk.

    While you can specify a Domain attribute, the specification says "The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server."

    Since the origin server is a.com and that does not include b.com, it can't be set.

    You would need to get b.com to set the cookie instead. You could do this via (for example) HTTP redirects to b.com and back.

    0 讨论(0)
  • 2020-11-22 07:55

    Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.

    1. Site A generates a token and passes as a URL parameter to site B.
    2. Site B takes the token and sets it as a session cookie.

    You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.

    0 讨论(0)
提交回复
热议问题