我可能更愿意在发送消息之前检查用户的权限,但是让我们想想如果它不是一个合适的情况我们可以如何处理。
为了检查用户权限,您需要对用户进行身份验证。但是,如果您异步使用消息或执行控制台命令,这并不简单,因为您没有实际用户。但是,您可以将用户 ID 与您的消息一起传递或传递给控制台命令。
让我分享一下我对Symfony Messenger的简单解决方案的想法。在 Symfony Messenger 中,有一个Stamps的概念,它允许您将元数据添加到您的消息中。在我们的例子中,将用户 ID 与消息一起传递会很有用,因此我们可以在消息处理过程中对用户进行身份验证。
让我们创建一个自定义标记来保存用户 ID。这是一个简单的 PHP 类,因此无需将其注册为服务。
<?php
namespace App\Messenger\Stamp;
use Symfony\Component\Messenger\Stamp\StampInterface;
class AuthenticationStamp implements StampInterface
{
private $userId;
public function __construct(string $userId)
{
$this->userId = $userId;
}
public function getUserId(): string
{
return $this->userId;
}
}
现在我们可以将戳记添加到消息中。
$message = new SampleMessage($payload);
$this->messageBus->dispatch(
(new Envelope($message))
->with(new AuthenticationStamp($userId))
);
我们需要接收和处理印章以验证用户身份。Symfony Messenger 有一个Middlewares的概念,所以让我们创建一个来处理来自 worker 的消息时的戳记。它会检查消息是否包含 AuthenticationStamp 并在用户当前未通过身份验证时对用户进行身份验证。
<?php
namespace App\Messenger\Middleware;
use App\Messenger\Stamp\AuthenticationStamp;
use App\Repository\UserRepositoryInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AuthenticationMiddleware implements MiddlewareInterface
{
private $tokenStorage;
private $userRepository;
public function __construct(TokenStorageInterface $tokenStorage, UserRepositoryInterface $userRepository)
{
$this->tokenStorage = $tokenStorage;
$this->userRepository = $userRepository;
}
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
/** @var AuthenticationStamp|null $authenticationStamp */
if ($authenticationStamp = $envelope->last(AuthenticationStamp::class)) {
$userId = $authenticationStamp->getUserId();
$token = $this->tokenStorage->getToken();
if (null === $token || $token instanceof AnonymousToken) {
$user = $this->userRepository->find($userId);
if ($user) {
$this->tokenStorage->setToken(new UsernamePasswordToken(
$user,
null,
'provider',
$user->getRoles())
);
}
}
}
return $stack->next()->handle($envelope, $stack);
}
}
让我们将其注册为服务(或自动装配)并包含在 messenger 配置定义中。
framework:
messenger:
buses:
messenger.bus.default:
middleware:
- 'App\Messenger\Middleware\AuthenticationMiddleware'
差不多就是这样。现在您应该能够使用常规方式检查用户的权限,例如选民。
至于控制台命令,我会使用身份验证服务,如果将用户 ID 传递给命令,它将对用户进行身份验证。