首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将access_control设置为不允许具有“ROLE_USER”的用户在成功登录后访问路径:^/登录?

如何将access_control设置为不允许具有“ROLE_USER”的用户在成功登录后访问路径:^/登录?
EN

Stack Overflow用户
提问于 2019-03-27 04:48:38
回答 2查看 103关注 0票数 1

security.yaml文件中,我们定义了各种路由的访问控制,以及可以访问同一路由的角色。

但是,我们如何设置已登录但不能重新访问/login页面的用户,除非它注销并将"ROLE_USER“更改为"anon”。

我刚接触过Symfony 4.2。

控制器:

代码语言:javascript
复制
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...
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-27 09:21:31

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

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

只需在方法login中调整SecurityController的if条件块即可。

代码语言:javascript
复制
if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY)) {
    $this->redirectToRoute('name of the route - replace with an appropriate value');
}

您应该注意重定向到的路径不会导致另一个重定向,从而使您处于一个无穷无尽的循环中。

票数 1
EN

Stack Overflow用户

发布于 2019-03-27 05:18:17

不能通过编辑security.yml拒绝登录用户对登录页的访问。所有使用Symfony应用程序的用户,无论是否登录,都将拥有基本访问权限:IS_AUTHENTICATED_ANONYMOUSLY和Symfony不具有不登录用户的独占角色。

但是,您可以通过检查用户是否已登录控制器并执行重定向或抛出AccessDeniedException来实现相同的目标。

代码语言:javascript
复制
public function login($name, AuthorizationCheckerInterface $authChecker)
{
    if ($authChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
        throw new AccessDeniedException('Logged in user cannot access this page');
    }

    // ...
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55369980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档