symfony 8.2中,isgranted的subject读取maprequestpayload等映射参数时,会先完成该参数的映射与验证,再把dto交给voter。要保留“未授权用户先被挡住”的行为,应把不依赖dto的身份检查写在前面,再声明以dto为subject的业务检查。以下用于已具备登录防火墙、serializer、validator和securitybundle的8.2测试应用,不包含登录系统搭建。
先定义要验证的请求对象
采用8.2.0-BETA2或包含PR66634的8.2构建,PHP至少8.4.1;相关组件保持同一兼容版本线。示例用非空title作为基本输入约束:
<?php
// src/Dto/PostDto.php
namespace App\Dto;
use Symfony\Component\Validator\Constraints as Assert;
final readonly class PostDto
{
public function __construct(#[Assert\NotBlank] public string $title = '') {}
}按顺序声明两层检查
post必须与控制器参数$post的名称一致。第一层只检查身份,第二层才读取映射对象。下面的返回值用于演示检查是否通过,不执行数据库写入:
<?php
// src/Controller/PostController.php
namespace App\Controller;
use App\Dto\PostDto;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
final class PostController extends AbstractController
{
#[Route('/posts', name: 'post_create', methods: ['POST'], format: 'json')]
#[IsGranted('IS_AUTHENTICATED')]
#[IsGranted('POST_CREATE', 'post')]
public function create(#[MapRequestPayload] PostDto $post): JsonResponse
{
return $this->json(['accepted' => true, 'title' => $post->title]);
}
}
官方公告列出的IsGranted声明顺序及映射后投票规则。
Voter接收的是PostDto
默认Symfony应用的服务配置启用autowire和autoconfigure时,src/Security中的Voter可自动注册。示例策略只允许已登录且具有ROLE_EDITOR的用户;实际项目应替换为自身业务规则,不因DTO类型正确就一律放行。
<?php
// src/Security/PostCreateVoter.php
namespace App\Security;
use App\Dto\PostDto;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
final class PostCreateVoter extends Voter
{
public function __construct(private readonly Security $security) {}
protected function supports(string $attribute, mixed $subject): bool
{
return $attribute === 'POST_CREATE' && $subject instanceof PostDto;
}
protected function voteOnAttribute(
string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null
): bool {
return $token->getUser() instanceof UserInterface
&& $this->security->isGranted('ROLE_EDITOR');
}
}
官方Voter参考示例的浏览器翻译视图,展示用户、subject与投票方法。
旧实现若把映射属性本身作为subject检查,升级后必须调整对应类型判断和业务代码。保留框架当前支持的Vote可选参数签名;不能只改控制器而让旧Voter继续按原类型分支处理。
在测试环境核对四种路径
未登录请求应先由现有防火墙和身份检查拒绝或进入登录流程;已登录但title为空时应先得到映射验证错误,MapRequestPayload默认使用422;已登录、输入合法但没有ROLE_EDITOR时应得到拒绝访问;具有相应权限且输入合法时,才进入示例控制器返回JSON。
可用测试环境的日志或测试替身确认Voter收到PostDto,而不是仅比较HTTP状态。现有防火墙的入口点可能影响未登录请求表现,不能把重定向误判为映射未生效。不要为了让业务Voter先运行而移除输入验证:8.2这项变化正是先构造有效对象,再对它执行授权判断。


















