我可以在 symfony 中创建类似于 isGranted 的东西吗?

所以基本上我想创建类似@IsGranted@IsGranted例如,我在我的应用程序上使用访问控制来防止简单用户访问管理页面。

在我的实体上,我有一个名为is_Active

  • 如果为真 (1),则用户可以使用他的帐户

  • 如果它是 false (0) 那么他会被重定向到一个错误页面!

在这种情况下,我不会在Roles用户现场进行测试,但我会在is_Active现场进行测试,这就是为什么我不能使用 @IsGranted.

我创建了一个错误的树枝页面并将其放在模板文件夹中,我发现自己被迫在每个active.html.twig控制器函数 上添加这两行。

if ($this->getUser()->getIsActive()==false) {

     return $this->render('active.html.twig');}

这是一个例子:


/**

 * @IsGranted("ROLE_ADMIN")

 * @Route("/", name="user_index", methods={"GET"})

 */

public function index(UserRepository $userRepository): Response

{

    if ($this->getUser()->getIsActive()==false) {

        return $this->render('active.html.twig');}

            

    return $this->render('user/index.html.twig', [

        'users' => $userRepository->findAll(),

    ]);

}

在每个函数上添加这个 if 语句是非常繁重和糟糕的(我在应用程序上有 +30 个函数)


也许我可以创建类似的东西@IsGranted并在每个函数的注释上使用它?


慕容森
浏览 190回答 2
2回答

叮当猫咪

您可以继续将 @IsGranted 与自定义选民一起使用。https://symfony.com/doc/current/security/voters.html#creating-the-custom-voter像文档中那样创建新选民public const ACTIVE = 'active';protected function supports(string $attribute, $subject){    return $attribute === self::ACTIVE;}protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token){    $user = $token->getUser();    if ($user instanceof User && !$user->isActive()) {        throw new InactiveUserException();    }    return true;}然后你可以为客户创建一个监听器InactiveUserException并向客户展示你想要的东西。在您的控制器中,您需要在路由方法或控制器之前放置@IsGranted("active")或@Security(expression="is_granted('active')")

慕姐4208626

我会为此使用身份验证,这样您就不必触摸您的控制器。您可以检查他们是否已登录并处于活动状态,然后他们可以查看内容,或者如果他们未通过身份验证,则您可以使用 active.html.twig 将他们定向到另一条路线。您也可以只在某些路线或所有路线上设置此设置。https://symfony.com/doc/current/security/guard_authentication.html示例 Authenticator 并仅为您的管理路由设置它,然后您可以拥有一个普通的身份验证器,而无需在所有其他路由的 checkCredentials 上检查活动用户。<?phpnamespace App\Security;use App\Entity\User;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Exception\AuthenticationException;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;use Twig\Environment;class AdminAuthenticator extends AbstractGuardAuthenticator{&nbsp; &nbsp; /** @var Environment */&nbsp; &nbsp; private $twig;&nbsp; &nbsp; public function __construct(Environment $twig)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $this->twig = $twig;&nbsp; &nbsp; }&nbsp; &nbsp; public function supports(Request $request): bool&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $email = $request->request->get('email');&nbsp; &nbsp; &nbsp; &nbsp; $password = $request->request->get('password');&nbsp; &nbsp; &nbsp; &nbsp; return $email && $password;&nbsp; &nbsp; }&nbsp; &nbsp; public function getCredentials(Request $request)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $email = $request->request->get('email');&nbsp; &nbsp; &nbsp; &nbsp; $password = $request->request->get('password');&nbsp; &nbsp; &nbsp; &nbsp; return [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'email' => $email,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'password' => $password&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }&nbsp; &nbsp; public function getUser($credentials, UserProviderInterface $userProvider)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $email = $credentials['email'];&nbsp; &nbsp; &nbsp; &nbsp; return $userProvider->loadUserByUsername($email);&nbsp; &nbsp; }&nbsp; &nbsp; public function checkCredentials($credentials, UserInterface $user)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; $password = $credentials['password'];&nbsp; &nbsp; &nbsp; &nbsp; if (!$this->passwordEncoder->isPasswordValid($user, $password)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new CustomUserMessageAuthenticationException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Sorry, you\'ve entered an invalid username or password.'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; if (!$user->isActive()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new NotActiveUserException(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'This account is not active'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; public function onAuthenticationFailure(Request $request, AuthenticationException $exception)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ($exception instanceof NotActiveUserException) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // You should redirect here but you get the idea!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $this->twig->render('active.html.twig');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // Do something else for any other failed auth&nbsp; &nbsp; }&nbsp; &nbsp; public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new JsonResponse('success', Response::HTTP_OK);&nbsp; &nbsp; }&nbsp; &nbsp; public function start(Request $request, AuthenticationException $authException = null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new JsonResponse('Not Authorized', Response::HTTP_UNAUTHORIZED);&nbsp; &nbsp; }&nbsp; &nbsp; public function supportsRememberMe()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}然后在你的 security.yaml&nbsp; &nbsp; firewalls:&nbsp; &nbsp; &nbsp; &nbsp; admin:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pattern: ^/admin&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; provider: user&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; guard:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; authenticators:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; - App\Security\AdminAuthenticator
打开App,查看更多内容
随时随地看视频慕课网APP