Cookie 跨域问题

This commit is contained in:
柳清爽
2025-04-29 10:13:02 +08:00
parent 0f995b09cb
commit 559bbab6cb
3 changed files with 74 additions and 3 deletions

View File

@@ -0,0 +1,32 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Cookie设置
// +----------------------------------------------------------------------
return [
// cookie 名称前缀
'prefix' => '',
// cookie 保存时间
'expire' => 0,
// cookie 保存路径
'path' => '/',
// cookie 有效域名
'domain' => '',
// cookie 启用安全传输
'secure' => false,
// httponly设置
'httponly' => '',
// 是否使用 setcookie
'setcookie' => true,
// 跨站需要
'SameSite' => 'None',
];

View File

@@ -94,8 +94,47 @@ class AuthLoginController extends Controller
*/
protected function setCookie(AdministratorModel $admin): void
{
cookie('admin_id', $admin->id, 86400);
cookie('admin_token', $this->createToken($admin), 86400);
// 获取当前环境
$env = app()->env->get('APP_ENV', 'production');
// 获取请求的域名
$origin = $this->request->header('origin');
$domain = '';
if ($origin) {
// 解析域名
$parsedUrl = parse_url($origin);
if (isset($parsedUrl['host'])) {
// 如果是测试环境,使用完整的域名
if ($env === 'testing') {
$domain = $parsedUrl['host'];
} else {
// 生产环境使用顶级域名
$parts = explode('.', $parsedUrl['host']);
if (count($parts) > 1) {
$domain = '.' . $parts[count($parts)-2] . '.' . $parts[count($parts)-1];
}
}
}
}
// 设置cookie选项
$options = [
'expire' => 86400,
'path' => '/',
'httponly' => true,
'samesite' => 'None', // 允许跨域
'secure' => true // 仅 HTTPS 下有效
];
// 如果有域名,添加到选项
if ($domain) {
$options['domain'] = $domain;
}
// 设置cookies
\think\facade\Cookie::set('admin_id', $admin->id, $options);
\think\facade\Cookie::set('admin_token', $this->createToken($admin), $options);
}
/**

View File

@@ -28,5 +28,5 @@ return [
// 是否使用 setcookie
'setcookie' => true,
// 跨站需要
'samesite' => 'None',
'SameSite' => 'None',
];