在security.yaml文件中,我们定义了各种路由的访问控制,以及可以访问同一路由的角色。
但是,我们如何设置已登录但不能重新访问/login页面的用户,除非它注销并将"ROLE_USER“更改为"anon”。
我刚接触过Symfony 4.2。
控制器:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
//use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="login")
*/
public function login(Request $request, AuthenticationUtils $utils, AuthorizationCheckerInterface $authChecker)
{
// to check whether user is looged-in
if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
die('Logged in user cannot access this page');
}
// get the login error if there is one
$error = $utils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $utils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
public function logout()
{
# code...
}发布于 2019-03-27 09:21:31
正如我在评论中提到的,在我看来,向已经登录的用户抛出一个AccessDeniedException并不是一个好方法。你的用户会怎么想?如果我已经登录了,为什么我不能访问一个页面,即使我没有登录,也可以正常访问。
因此,我强烈建议在访问/login路径时将登录用户重定向到应用程序的起始页面。
只需在方法login中调整SecurityController的if条件块即可。
if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY)) {
$this->redirectToRoute('name of the route - replace with an appropriate value');
}您应该注意重定向到的路径不会导致另一个重定向,从而使您处于一个无穷无尽的循环中。
发布于 2019-03-27 05:18:17
不能通过编辑security.yml拒绝登录用户对登录页的访问。所有使用Symfony应用程序的用户,无论是否登录,都将拥有基本访问权限:IS_AUTHENTICATED_ANONYMOUSLY和Symfony不具有不登录用户的独占角色。
但是,您可以通过检查用户是否已登录控制器并执行重定向或抛出AccessDeniedException来实现相同的目标。
public function login($name, AuthorizationCheckerInterface $authChecker)
{
if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
throw new AccessDeniedException('Logged in user cannot access this page');
}
// ...
}https://stackoverflow.com/questions/55369980
复制相似问题