Programming

명시 적 도메인을 가진 localhost의 쿠키

procodes 2020. 5. 26. 21:48
반응형

명시 적 도메인을 가진 localhost의 쿠키


쿠키에 대한 몇 가지 기본 사항이 누락되어 있어야합니다. 나는 서버 측에 쿠키를 설정 로컬 호스트에 로컬 호스트 (또는 .localhost) 명시 적으로 도메인을 지정합니다. 쿠키가 일부 브라우저에서 허용되지 않는 것 같습니다.

Firefox 3.5 : Firebug에서 HTTP 요청을 확인했습니다. 내가 보는 것은 :

Set-Cookie:
    name=value;
    domain=localhost;
    expires=Thu, 16-Jul-2009 21:25:05 GMT;
    path=/

또는 (도메인을 .localhost로 설정 한 경우) :

Set-Cookie:
    name=value;
    domain=.localhost;
    expires=Thu, 16-Jul-2009 21:25:05 GMT;
    path=/

두 경우 모두 쿠키가 저장되지 않습니다.

IE8 : 추가 도구를 사용하지 않았지만 쿠키가 후속 요청에서 다시 전송되지 않기 때문에 쿠키도 저장되지 않은 것 같습니다.

Opera 9.64 : localhost와 .localhost 모두 작동 하지만 Preferences에서 쿠키 목록을 확인하면 도메인이 localhost (목록 그룹화) 아래에 나열되어 있어도 도메인은 localhost.local로 설정됩니다.

Safari 4 : localhost와 .localhost는 모두 작동 하지만 환경 설정에서 항상 .localhost로 표시됩니다. 반면에 명시 적 도메인이없는 쿠키는 로컬 호스트 (점 없음)로 표시됩니다.

localhost의 문제점은 무엇입니까? 이러한 불일치로 인해 localhost와 관련된 특수 규칙이 있어야합니다. 또한 왜 도메인 앞에 점이 붙어야하는지 명확하지 않습니다. RFC 2109는 명시 적으로

Domain 속성 값에 포함 된 점이 없거나 점으로 시작하지 않습니다.

왜? 이 문서에는 보안 관련 작업이 필요하다는 내용이 나와 있습니다. 나는 전체 사양을 읽지 않았다는 것을 인정해야하지만 (나중에 할 수도 있음) 조금 이상하게 들립니다. 이를 기반으로 localhost에서 쿠키를 설정하는 것은 불가능합니다.


설계 상 도메인 이름에는 최소한 두 개의 점이 있어야합니다. 그렇지 않으면 브라우저가 유효하지 않은 것으로 간주합니다. ( http://curl.haxx.se/rfc/cookie_spec.html의 참조를 참조 하십시오 )

작업시 localhost쿠키 도메인은 완전히 생략해야합니다. 그냥으로 설정 ""하거나 NULL또는 FALSE대신하는 것은 "localhost"충분하지 않습니다.

PHP의 경우 http://php.net/manual/en/function.setcookie.php#73107에 대한 주석을 참조 하십시오 .

Java Servlet API로 작업하는 경우 cookie.setDomain("...")메소드를 전혀 호출하지 마십시오 .


@Ralph Buchfelder에 광범위하게 동의하지만 로컬 컴퓨터 (example.com, fr.example.com, de.example.com과 같은 여러 하위 도메인이있는 시스템을 복제하려고 할 때 실험을 통해이를 증폭시키는 방법이 있습니다) OS X / Apache / Chrome | Firefox).

127.0.0.1에서 가상의 하위 도메인을 가리 키도록 / etc / hosts를 편집했습니다.

127.0.0.1 localexample.com
127.0.0.1 fr.localexample.com
127.0.0.1 de.localexample.com

fr.localexample.com에서 작업 중이고 domain 매개 변수를 제외하면 fr.localexample.com에 쿠키가 올바르게 저장되지만 다른 하위 도메인에는 표시되지 않습니다.

나는 ".localexample.com"의 도메인을 사용하는 경우, 쿠키가 fr.localexample.com 제대로 저장되고 있다 다른 하위 도메인에 표시.

"localexample.com"도메인을 사용하거나 "localexample"또는 "localhost"도메인을 시도 할 때 쿠키가 저장되지 않았습니다.

"fr.localexample.com"또는 ".fr.localexample.com"도메인을 사용하는 경우 쿠키는 fr.localexample.com에 대해 올바르게 저장되고 다른 하위 도메인에 (올바르게) 보이지 않습니다.

따라서 도메인에 두 개 이상의 점이 필요하다는 요구 사항은 왜 그래야하는지 알 수 없지만 올바른 것으로 보입니다.

누군가 이것을 시도하고 싶다면 다음과 같은 유용한 코드가 있습니다.

<html>
<head>
<title>
Testing cookies
</title>
</head>
<body>
<?php
header('HTTP/1.0 200');
$domain = 'fr.localexample.com';    // Change this to the domain you want to test.
if (!empty($_GET['v'])) {
    $val = $_GET['v'];
    print "Setting cookie to $val<br/>";
    setcookie("mycookie", $val, time() + 48 * 3600, '/', $domain);
}
print "<pre>";
print "Cookie:<br/>";
var_dump($_COOKIE);
print "Server:<br/>";
var_dump($_SERVER);
print "</pre>";
?>
</body>
</html>

localhost : 당신은 사용할 수 있으며 domain: ".app.localhost"작동합니다. '도메인'매개 변수는 1 개 이상의 점을 필요로 쿠키를 설정하기위한 도메인 이름. 그런 다음 다음과 같은 로컬 호스트 하위 도메인에서 세션을 작동시킬 수 있습니다 api.app.localhost:3000.


When a cookie is set with an explicit domain of 'localhost' as follows...

Set-Cookie: name=value; domain=localhost; expires=Thu, 16-Jul-2009 21:25:05 GMT; path=/

...then browsers ignore it because it does not include at least two periods and is not one of seven specially handled, top level domains.

...domains must have at least two (2) or three (3) periods in them to prevent domains of the form: ".com", ".edu", and "va.us". Any domain that fails within one of the seven special top level domains listed below only require two periods. Any other domain requires at least three. The seven special top level domains are: "COM", "EDU", "NET", "ORG", "GOV", "MIL", and "INT".

Note that the number of periods above probably assumes that a leading period is required. This period is however ignored in modern browsers and it should probably read...

at least one (1) or two (2) periods

Note that the default value for the domain attribute is the host name of the server which generated the cookie response.

So a workaround for cookies not being set for localhost is to simply not specify a domain attribute and let the browser use the default value - this does not appear to have the same constraints that an explicit value in the domain attribute does.


Results I had varied by browser.

Chrome- 127.0.0.1 worked but localhost .localhost and "" did not. Firefox- .localhost worked but localhost, 127.0.0.1, and "" did not.

Have not tested in Opera, IE, or Safari


Spent a great deal of time troubleshooting this issue myself.

Using PHP, and Nothing on this page worked for me. I eventually realized in my code that the 'secure' parameter to PHP's session_set_cookie_params() was always being set to TRUE.

Since I wasn't visiting localhost with https my browser would never accept the cookie. So, I modified that portion of my code to conditionally set the 'secure' param based on $_SERVER['HTTP_HOST'] being 'localhost' or not. Working well now.

I hope this helps someone.


I had much better luck testing locally using 127.0.0.1 as the domain. I'm not sure why, but I had mixed results with localhost and .localhost, etc.


None of the suggested fixes worked for me - setting it to null, false, adding two dots, etc - didn't work.

In the end, I just removed the domain from the cookie if it is localhost and that now works for me in Chrome 38.

Previous code (did not work):

document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';

New code (now working):

 if(document.domain === 'localhost') {
        document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';path=/;' ;
    } else {
        document.cookie = encodeURI(key) + '=' + encodeURI(value) + ';domain=.' + document.domain + ';path=/;';
    }

I had the same issue and I fixed it by putting 2 dots in the cookie name itself without specifying any domain.

set-cookie: name.s1.s2=value; path=/; expires=Sun, 12 Aug 2018 14:28:43 GMT; HttpOnly

There seems to be an issue when you use https://<local-domain> and then http://<local-domain>. The http:// site does not send cookies with requests after https:// site sets them. Force reload and clear cache doesn't help. Only manual clearing of cookies works. Also, if I clear them on the https:// page, then http:// page starts working again.

Looks to be related to "Strict secure cookies". Good explanation here. It was released in Chrome 58 on 2017-04-19.

It looks like Chrome does in fact record both secure cookies and non-secure cookies as it will show the correct cookies depending on the page's protocol when clicking the address bar icon.

But Developer tools > Application > Cookies will not show a non-secure cookie when there is a secure cookie of the same name for the same domain, nor will it send the non-secure cookie with any requests. This seems like a Chrome bug, or if this behavior is expected, there should be some way to view the secure cookies when on a http page and an indication that they are being overridden.

Workaround is to use different named cookies depending on if they are for an http site or https site, and to name them specific to your app. A __Secure- prefix indicates that the cookie should be strictly secure, and is also a good practice because secure and non-secure won't collide. There are other benefits to prefixes too.

Using different /etc/hosts domains for https vs. http access would work too, but one accidental https://localhost visit will prevent any cookies of the same names to work on http://localhost sites - so this is not a good workaround.

I have filed a Chrome bug report.


you can make use of localhost.org or rather .localhost.org it will always resolve to 127.0.0.1


document.cookie = valuename + "=" + value + "; " + expires + ";domain=;path=/";

this "domain=;path=/"; will take dynamic domain as its cookie will work in subdomain. if u want to test in localhost it will work


None of the answers here worked for me. I fixed it by putting my PHP as the very very first thing in the page.

Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.

From http://php.net/manual/en/function.setcookie.php


There is an issue on Chromium open since 2011, that if you are explicitly setting the domain as 'localhost', you should set it as false or undefined.


I was playing around a bit.

Set-Cookie: _xsrf=2|f1313120|17df429d33515874d3e571d1c5ee2677|1485812120; Domain=localhost; Path=/

works in Firefox and Chrome as of today. However, I did not find a way to make it work with curl. I tried Host-Header and --resolve, no luck, any help appreciated.

However, it works in curl, if I set it to

Set-Cookie: _xsrf=2|f1313120|17df429d33515874d3e571d1c5ee2677|1485812120; Domain=127.0.0.1; Path=/

instead. (Which does not work with Firefox.)


Another important detail, the expires= should use the following date time format: Wdy, DD-Mon-YYYY HH:MM:SS GMT (RFC6265 - Section 4.1.1).

Set-Cookie:
  name=value;
  domain=localhost;
  expires=Thu, 16-07-2019 21:25:05 GMT;
  path=/

If you're setting a cookie from another domain (ie you set the cookie by making an XHR cross origin request), then you need to make sure you set the withCredentials attribute to true on the XMLHttpRequest you use to fetch the cookie as described here

참고URL : https://stackoverflow.com/questions/1134290/cookies-on-localhost-with-explicit-domain

반응형