未定义的方法在 Symfony 4 中被授予
Undefined method isGranted in Symfony 4
我在 Symfony4 中使用来自 Symfony2 应用程序的语句:
$securityContext = $this->container->get('security.token_storage');
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){
. . .
}
我总是得到错误:
Attempted to call an undefined method named "isGranted" of class "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage
我错过了什么?
Symfony gives you several ways to enforce authorization, including […] using isGranted
on the security.authorization_checker
service directly.
您应该在 security.authorization_checker
服务上调用 isGranted
,而不是 security.token_storage
。
对于 SF4,根据文档:
public function hello($name)
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
// ...
}
您必须使用 security.authorization_checker 服务。而上面的代码是一样的:
public function hello($name, AuthorizationCheckerInterface $authChecker)
{
if (false === $authChecker->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException('Unable to access this page!');
}
// ...
}
在此处查看文档 https://symfony.com/doc/4.0/security.html#securing-controllers-and-other-code
我在 Symfony4 中使用来自 Symfony2 应用程序的语句:
$securityContext = $this->container->get('security.token_storage');
if($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') ){
. . .
}
我总是得到错误:
Attempted to call an undefined method named "isGranted" of class "Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage
我错过了什么?
Symfony gives you several ways to enforce authorization, including […] using
isGranted
on thesecurity.authorization_checker
service directly.
您应该在 security.authorization_checker
服务上调用 isGranted
,而不是 security.token_storage
。
对于 SF4,根据文档:
public function hello($name)
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_REMEMBERED');
// ...
}
您必须使用 security.authorization_checker 服务。而上面的代码是一样的:
public function hello($name, AuthorizationCheckerInterface $authChecker)
{
if (false === $authChecker->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException('Unable to access this page!');
}
// ...
}
在此处查看文档 https://symfony.com/doc/4.0/security.html#securing-controllers-and-other-code