0

我目前尝试在 Symfony 5 中使用 Mercure。我根据文档(https://symfony.com/doc/current/mercure.html)使用 symfony/mercure 包。

我在 Ubuntu 20.04 上,它基于 Docker env(Apache2、PHP8、Mercure 0.13.0、Symfony 5.3)。这是美居 docker-compose 容器

mercure:
        image: dunglas/mercure
        container_name: mercure
        restart: unless-stopped
        ports:
            - "81:80"
        environment:
            MERCURE_PUBLISHER_JWT_KEY: '!ChangeMe!'
            MERCURE_SUBSCRIBER_JWT_KEY: '!ChangeMe!'
            CORS_ALLOWED_ORIGINS: '*'
            MERCURE_CORS_ALLOWED_ORIGINS: '*'
            PUBLISH_ALLOWED_ORIGINS: '*'
            ALLOW_ANONYMOUS: '1'
            MERCURE_EXTRA_DIRECTIVES: cors_origins *
            SERVER_NAME: ":80"
        command: /usr/bin/caddy run -config /etc/caddy/Caddyfile.dev
        volumes:
            - mercure_data:/data
            - mercure_config:/config
        networks:
            - server

我成功地将更新发送到我的树枝页面。但是当我尝试通过这种方式在订阅上使用授权时

/**
     * @Route("/ping/{user}", name="ping", methods={"POST"})
     */
    public function ping(HubInterface $hub, ?User $user = null): Response
    {
        
            $update = new Update(
                'user/' . $user->getId(),
                json_encode(['message' => 'PING FROM ' . $this->getUser()->getUserIdentifier() . ' TO ' . $user->getUserIdentifier() .  ' !']),
                true
            );

        $hub->publish($update);

        return $this->redirectToRoute('index');
    }
const eventSource = new EventSource("{{ mercure('user/' ~ app.user.id, { subscribe: 'user/' ~ app.user.id })|escape('js') }}", {
    withCredentials: true
});

eventSource.onmessage = e => {
    console.log('HELLO');
};

美居 yaml 配置

mercure:
    hubs:
        default:
            url: '%env(MERCURE_URL)%'
            public_url: '%env(MERCURE_PUBLIC_URL)%'
            jwt:
                secret: '%env(MERCURE_JWT_SECRET)%'
                publish: '*'
                provider: App\Service\MercureJwtProvider

配置中使用的 MercureJwtProvider

<?php

namespace App\Service;

use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Symfony\Component\Mercure\Jwt\TokenProviderInterface;

class MercureJwtProvider implements TokenProviderInterface
{
    private string $secret;

    public function __construct(string $secret)
    {
        $this->secret = $secret;
    }

    public function getJwt(): string
    {
        $configuration = Configuration::forSymmetricSigner(
            new Sha256(),
            InMemory::plainText($this->secret)
        );

        return $configuration
            ->builder()
            ->withClaim('mercure', ['publish' => ['*']])
            ->getToken(
                $configuration->signer(),
                $configuration->signingKey()
            )
            ->toString();
    }
}

我收到此错误 => https://i.stack.imgur.com/aD6gP.png

如果有人遇到此错误并且可以帮助我...

谢谢 !

4

0 回答 0