React:重定向到子域时保留 cookie

React: Preserve cookies when redirecting to sub-domain

我需要在成功验证后将用户重定向到它自己的子域,例如

company.test.com 来自 test.com

授权页面在 test.com 打开,当我收到成功授权的响应时,我从数据库中获取了用户的子域名。所以公司名称xyz应该重定向到xzy.test.com那部分已经完成了

问题出在用户的会话上。我将经过身份验证的用户数据保存到 redux 中,当页面 refreshes/redirects 到子域时,它会丢失用户数据。

我能想到的是,我应该将经过身份验证的用户 id 和子域(如 xyz.test.com/encrypted-user-id )一起传递给路由,然后我将在后端获取该用户 ID,然后将解密它并强制用户登录而无需再次询问密码。

我的问题是...有其他方法吗?如果不是,这是解决这个问题的可行方法

是的,有另一种更正确的方法来解决您的问题。

我将尝试分两部分回答:首先在 root- 和 sub-domains 之间启用 cookie,其次如何在 Laravel 中执行此操作。

使 cookie 在 root 和 sub-domains 之间可用:

当收到 cookie headers 时,可以指示浏览器跨子域共享 cookie。这是通过将域添加到 Set-Cookie header.

来实现的
Set-Cookie: user=JohnDoe; domain=testdomain.com

RFC-6265, the above syntax will tell the browser that cookies set on test.com should be made available to all subdomains (i.e. a.test.com, xyz.test.com). For a more detailed explanation see this answer 开始。

将 cookie 设置为在 Laravel:

的子域上可用

根据 Laravel responses documentationcookie 函数接受 php 的 [setcookie][4] 函数接受的所有参数(查看 pathdomain 参数)。

举个例子,对于 one off 你可以这样写:

$path = '/'; // make cookie available on all paths
$domain = "test.com";  // according to rfc6265 make available on root and subdomains
return $response($content)->cookie($name, $value, $minutes, $path, $domain);

另一种方式,在根域和子域之间共享所有 cookie 来自 JacobBennet's snippet。那里的建议是在 config/session.php 中设置 domain 变量的所需值。然后,所有 (!) cookie 将可用于子域。

除了“重定向”之外,前端 (React) 不应该做任何特别的事情。