API-Platform中基于角色的结果的最佳方式
创始人
2024-09-07 05:00:38
0

使用Symfony Security组件实现基于角色的访问控制,配合API-Platform的自定义数据提供程序实现角色过滤。

首先,在Symfony Security中定义角色:

// src/Security/CustomUserChecker.php
namespace App\Security;

use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;

class CustomUserChecker implements UserCheckerInterface
{
    public function checkPreAuth(UserInterface $user)
    {
        // ...
    }

    public function checkPostAuth(UserInterface $user)
    {
        if (!$user->getEnabled()) {
            // 用户已禁用
            throw new CustomUserMessageAuthenticationException('user.disabled');
        }
    }
}

api/config/packages/security.yaml中配置Symfony Security,启用角色验证:

# api/config/packages/security.yaml
security:
    # ...
    role_hierarchy:
        ROLE_ADMIN: [ROLE_USER]
    providers:
        custom_provider:
            entity:
                class: App\Entity\User
                property: email
        # ...
    firewalls:
        main:
            # ...
            pattern: ^/
            anonymous: ~
            # 添加认证器
            guard:
                authenticators:
                    - App\Security\CustomAuthenticator
            # 配置登陆、注销路由
            logout:
                path: app_logout
                target: /
    # ...

在自定义数据提供程序中实现角色过滤:

// src/DataProvider/UserDataProvider.php
namespace App\DataProvider;

use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Entity\User;
use App\Repository\UserRepositoryInterface;
use Symfony\Component\Security\Core\Security;

class UserDataProvider implements ContextAwareCollectionDataProviderInterface, RestrictedDataProviderInterface
{
    private $userRepository;
    private $security;

    public function __construct(UserRepositoryInterface $userRepository, Security $security)
    {
        $this->userRepository = $userRepository;
        $this->security = $security;
    }

    public function getCollection(string $resourceClass, string $operationName = null, array

相关内容

热门资讯

技巧知识分享!蘑菇云辅助怎么使... 技巧知识分享!蘑菇云辅助怎么使用,微信神兽大厅源代码,详细技巧(有挂教学)微信神兽大厅源代码破解侠是...
重大通报!陕西三代攻略,雀神广... 重大通报!陕西三代攻略,雀神广东麻将必赢方法,详细插件(讲解有挂)1、下载好雀神广东麻将必赢方法正确...
教程辅助!随意玩俱乐部辅助,皇... 教程辅助!随意玩俱乐部辅助,皇豪互娱控制系统,详细器(有挂技术)1、随意玩俱乐部辅助免费脚本咨询教程...
必看攻略!闽游app辅助器,枫... 必看攻略!闽游app辅助器,枫叶辅助官网下载,详细插件(今日头条)1、枫叶辅助官网下载破解器简单,枫...
科普!陕西辅助,微信雀神挂件辅... 科普!陕西辅助,微信雀神挂件辅助器,详细器(新版有挂)1、微信雀神挂件辅助器有没有辅助教程、微信雀神...
发现玩家!皮皮辅助软件下载,新... 发现玩家!皮皮辅助软件下载,新518互游插件,详细器(有挂方式)1、皮皮辅助软件下载脚本辅助下载、皮...
揭秘攻略!福建天天开心王国辅助... 揭秘攻略!福建天天开心王国辅助,潮友会辅助,详细工具(有挂存在)所有人都在同一条线上,像星星一样排成...
我来教大家!全民牛牛拼三张开挂... 我来教大家!全民牛牛拼三张开挂,河南微乐麻将小程序辅助器,详细app(有挂解惑)1、河南微乐麻将小程...
盘点一款!大菠萝辅助器,花花生... 盘点一款!大菠萝辅助器,花花生活圈开挂,详细器(讲解有挂)1、进入游戏-大厅左侧-新手福利-激活码辅...
实测交流!多乐找刺激辅助,雀友... 实测交流!多乐找刺激辅助,雀友会广东潮汕辅助软件,详细器(有挂总结);1、操作简单,无需雀友会广东潮...