1

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...
    }
4

2 回答 2

2

您不能通过编辑拒绝登录用户访问登录页面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');
    }

    // ...
}
于 2019-03-27T05:18:17.130 回答
1

正如我在评论中提到的,在我看来,AccessDeniedException向已经登录的用户抛出一个不是一个好方法。你的用户会怎么想?如果我已经登录了,为什么我不能访问一个即使我没有登录也可以正常访问的页面。

因此,我强烈建议在访问/login路径时将登录用户重定向到应用程序的起始页。

只需在login您的方法中调整 if-condition 块SecurityController

if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY)) {
    $this->redirectToRoute('name of the route - replace with an appropriate value');
}

您应该注意要重定向到的路线不会导致另一个重定向,从而使您陷入无限循环。

于 2019-03-27T09:21:31.673 回答