Session cookie not being preserved in the browser.

huangapple go评论66阅读模式
英文:

Session cookie not being preserved in the browser

问题

我今天联系你是因为我在我的网站上遇到了一个问题,它阻止我使用会话 Cookie 发送请求。让我详细解释一下情况。

我将我的网站托管在以下地址:https://www.coopratings.fr/。为了测试,你可以使用用户名 "a@a" 和密码 "a" 登录,并在导航栏中使用 "+" 按钮发布一款游戏。

当用户想在我的网站上执行某个操作时,会向服务器发送一个请求,服务器会使用 "session_start()" 函数和 "_SESSION["isLogged"]" 变量来检查用户是否已登录。

问题如下:在某些机器上,"phpsessid" Cookie 在请求之间保留不变,从而允许登录验证系统正常工作。但在其他机器上,"phpsessid" Cookie 在每个请求之间更改,这会阻止系统正常工作。

经过分析,我注意到每当浏览器在 "POST" 请求之前发送一个 "OPTIONS" 请求时,"phpsessid" Cookie 会更改,而我在浏览器的 "F12" 选项卡的 "Storage -> Cookies" 部分中看不到它被存储。

此外,当我在本地使用 XAMPP 托管我的网站时,使用的是 URL 127.0.0.1/mysite/...,一切都正常工作。但是,当我使用 phpStorm 显示页面时,它使用的是 URL http://localhost:63342/mySite/...,而浏览器会发送 "OPTIONS" 请求(这导致与前面提到的问题相同)。

当我以 localhost:63342/mySite/... 登录时,响应显示 "You are not logged in",因为我已经为未登录的 POST 请求配置了这个响应。

另一方面,当我登录到地址 coopratings.fr 时,控制台显示以下错误:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.coopratings.fr/Rest_API/...e_reviewid.php. (Reason: header 'content-type' is not allowed according to header 'Access-Control-Allow-Headers' from CORS preflight response)."

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.coopratings.fr/Rest_API/...e_reviewid.php. (Reason: CORS request did not succeed). Status code: (null)."

"Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource."

我已经在互联网上进行了广泛的研究,并尝试了不同的解决方案,但迄今为止,我还没有能够解决这个问题。以下是我迄今为止尝试过的内容:

  • 通过在我的 PHP 文件中处理 "OPTIONS" 请求,添加以下代码:
if (
    isset($_SERVER['REQUEST_METHOD'])
    && $_SERVER['REQUEST_METHOD'] === 'OPTIONS'
) {
    exit();
}
  • 使用以下配置修改响应头:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With, Accept, Cookie');
header('Access-Control-Allow-Credentials: true');
  • 在请求中添加 "mode: 'cors'" 和 "credentials: 'include'" 参数(不同时添加)。

  • 在会话创建期间修改 Cookie 参数:

public static function startSession(){
    $maxlifetime = 3600;
    $secure = true;
    $httponly = true;
    $samesite = 'None';

    if(PHP_VERSION_ID < 70300) {
        session_set_cookie_params($maxlifetime, '/; samesite='.$samesite, $_SERVER['HTTP_HOST'], $secure, $httponly);
    } else {
        session_set_cookie_params([
            'lifetime' => $maxlifetime,
            'path' => '/',
            'domain' => $_SERVER['HTTP_HOST'],
            'secure' => $secure,
            'httponly' => $httponly,
            'samesite' => $samesite
        ]);
    }

    session_start();
}
  • 这是我发送请求的方式:
let url = new URL('http://127.0.0.1/coopratings/Rest_API/api/');

return fetch(url + request, {
    method: type,
    body: body,
    headers: {
        "Content-Type": "application/json",
    }
})
.then(res => {
    return res.json();
})

希望能找到解决这个问题的办法。
提前感谢你的帮助。

英文:

I'm reaching out to you today because I'm facing an issue on my website that is preventing me from making requests using session cookies. Let me explain the situation in detail.

I host my website with a web host at the following address: https://www.coopratings.fr/. To test, you can log in with the username "a@a" and the password "a" and post a game with the "+" button in the navbar.

When a user wants to perform an action on my site, a request is sent to the server, which checks if the user is logged in using the "session_start()" function and the "_SESSION["isLogged"]" variable.

The problem is as follows: on some machines, the "phpsessid" cookie is preserved between requests, which allows the proper functioning of the login verification system. But on other machines, the "phpsessid" cookie changes with each request, which prevents the system from working correctly.

Upon analyzing the problem, I noticed that every time the browser sends an "OPTIONS" request before a "POST" request, the "phpsessid" cookie changes, and I don't see it stored in the "Storage -> Cookies" section of the browser's "F12" tab.

Furthermore, when I host my site locally with XAMPP using the URL 127.0.0.1/mysite/...&quot;, everything works correctly. However, when I use phpStorm to display the page, it uses the URL &quot;http://localhost:63342/mySite/...&quot;, and the browser sends "OPTIONS" requests (which causes the same problem as mentioned earlier).

When I'm logged locally with localhost:63342/mySite/...&quot;, the response displays "You are not logged in," as I have configured it for cases of logged-out POST requests.

On the other hand, when I log in to the address coopratings.fr, the console displays the following errors:

&quot;Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.coopratings.fr/Rest_API/...e_reviewid.php. (Reason: header &#39;content-type&#39; is not allowed according to header &#39;Access-Control-Allow-Headers&#39; from CORS preflight response).&quot;

&quot;Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.coopratings.fr/Rest_API/...e_reviewid.php. (Reason: CORS request did not succeed). Status code: (null).&quot;

&quot;Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.&quot;

I have done extensive research on the internet and have tried different solutions, but so far, I have not been able to resolve the issue. Here's what I have tried so far:

  • Handling "OPTIONS" requests in my PHP files by adding the following code:
if (
    isset($_SERVER[&#39;REQUEST_METHOD&#39;])
    &amp;&amp; $_SERVER[&#39;REQUEST_METHOD&#39;] === &#39;OPTIONS&#39;
) {
    exit();
}
  • Modifying the response headers with the following configurations:
header(&#39;Access-Control-Allow-Origin: *&#39;);
header(&#39;Access-Control-Allow-Methods: POST, OPTION&#39;);
header(&#39;Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With, Accept, Cookie&#39;);
header(&#39;Access-Control-Allow-Credentials: true&#39;);
  • Add the "mode: 'cors'" and "credentials: 'include'" parameters to the requests (not at the same time).

  • Modify the cookie parameters during session creation:

public static function startSession(){
    $maxlifetime = 3600;
    $secure = true;
    $httponly = true;
    $samesite = &#39;None&#39;;

    if(PHP_VERSION_ID &lt; 70300) {
        session_set_cookie_params($maxlifetime, &#39;/; samesite=&#39;.$samesite, $_SERVER[&#39;HTTP_HOST&#39;], $secure, $httponly);
    } else {
        session_set_cookie_params([
            &#39;lifetime&#39; =&gt; $maxlifetime,
            &#39;path&#39; =&gt; &#39;/&#39;,
            &#39;domain&#39; =&gt; $_SERVER[&#39;HTTP_HOST&#39;],
            &#39;secure&#39; =&gt; $secure,
            &#39;httponly&#39; =&gt; $httponly,
            &#39;samesite&#39; =&gt; $samesite
        ]);
    }

    session_start();
}
  • Here's how I send my requests:
let url = new URL(&#39;http://127.0.0.1/coopratings/Rest_API/api/&#39;);

return fetch(url + request, {
    method: type,
    body: body,
    headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
    }
})
.then(res =&gt; {
    return res.json();
})

Hoping to find a solution to this issue.
Thank you in advance for your help.

答案1

得分: 1

我已找到解决方案。
确保请求相同的来源。对我来说,问题是我忘记了加上 www。
并在你的请求中允许凭据。

英文:

Ok, I've found the solution.
Make sure to request the same origin. For me, it was that I've forgotten the www.
And allow credentials in your request

huangapple
  • 本文由 发表于 2023年6月22日 07:38:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定