问题描述
我一直在关注This documentation page,我想学习在Symfony中使用Mercure,并且一切顺利,直到到达“授权”部分。
bin / mercure.exe --jwt-algorithm ='HS256'--jwt-key ='konshensx'--addr ='localhost:3000'--allow-anonymous --cors-allowed-origins ='https :// localhost:8000'
我有一个端点可以发送测试更新。我将第三个参数设置为true,这样更新将仅发送到发送了有效载荷中具有相同主题的JWT的客户端
public function updateTest(PublisherInterface $publisher) {
$update = new Update(
'test',json_encode(['status' => 'something random']),true,// This thing make this update private
);
// The Publisher service is an invokable object
$publisher($update);
return $this->json(["testData" => "Monke"]);
}
这是我用来为模板提供正确JWT的代码,以便能够像文档一样查看更新并通过cookie发送
public function front(Request $request) {
$hubUrl = $this->getParameter('mercure.default_hub');
$this->addLink($request,new Link('mercure',$hubUrl));
$token = (new Builder())
// set other appropriate JWT claims,such as an expiration date
->withClaim('mercure',['subscribe' => ["test"]]) // can also be a URI template,or *
->getToken(new Sha256(),new Key($this->getParameter('mercure_secret_key'))); // don't forget to set this parameter! Test value: !ChangeMe!
$cookie = Cookie::create('mercureAuthorization')
->withValue($token)
->withPath('/.well-kNown/mercure')
->withSecure(true)
->withHttpOnly(true)
->withSameSite('strict')
;
$response = $this->render('conversation/index.html.twig');
$response->headers->setCookie($cookie);
return $response;
}
我的模板中有这个小代码,以获取默认的Mercure Hub链接
fetch('{{path('conversation.discover')}}').then(response => {
const hubUrl = response.headers.get('Link').match(/<([^>]+)>;\s+rel=(?:mercure|"[^"]*mercure[^"]*")/)[1];
// URL is a built-in JavaScript class to manipulate URLs
const url = new URL(hubUrl);
url.searchParams.append('topic','test');
const eventSource = new EventSource(url,{
withCredentials: true
});
eventSource.onmessage = event => {
console.log(JSON.parse(event.data));
}
});
这是模板要求Mercure Hub链接的端点
public function discover(PublisherInterface $publisher,Request $request) {
// This parameter is automatically created by the MercureBundle
$hubUrl = $this->getParameter('mercure.default_hub');
// $hubUrl = str_replace("localhost","127.0.0.1",$hubUrl);
// Link: <http://localhost:3000/.well-kNown/mercure>; rel="mercure"
$this->addLink($request,$hubUrl));
return $this->json(["testData" => "Monke"]);
}
这一切在Firefox中都可以正常工作,我还没有测试其他浏览器,因为这里的问题是Chrome无法正常工作(Edge似乎也无法正常工作,就像Chrome可以正常工作一样),它在以下情况下不会发送任何Cookie:即使我具有withCredentials = true,也会触发EventSource,实际上,似乎根本没有存储任何cookie!
这是EventSource的Chrome开发者工具中的“网络”标签
我也想让它也可以在Chrome中运行,但是请问我该怎么办。
我将项目中的每个URL更改为相同的域名“ localhost”,因此我读到“在一个域中设置的Cookie不会发送到其他域。尝试通过localhost或127.0.0.1访问这两个站点”另一个问题,但是还不能解决
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)