首页 文章

身份验证后symfony重定向用户

提问于
浏览
1

我有两个捆绑userBundle和xxxBundle . 我想在验证用户包中的用户后将其重定向到xxxBundle . 但是,根据角色(ROLE_ADMIN和ROLE_USER),我会将他重定向到两个不同的路由(route1,route2) .

我将此控制器添加到我的userBundle

class SecurityController extends Controller
{
  public function loginAction()
  {
    if ($this->get('security.context')->isGranted('ROLE_ADMIN')) {
      return $this->redirect($this->generateUrl('route1'));

    }
if ($this->get('security.context')->isGranted('ROLE_USER')) {
      return $this->redirect($this->generateUrl('route2'));

    }

    $request = $this->getRequest();
    $session = $request->getSession();

    // On vérifie s'il y a des erreurs d'une précédent soumission du formulaire
    if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
      $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    } else {
      $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
      $session->remove(SecurityContext::AUTHENTICATION_ERROR);
    }

    return $this->render('UserBundle:Security:login.html.twig', array(
      // Valeur du précédent nom d'utilisateur rentré par l'internaute
      'last_username' => $session->get(SecurityContext::LAST_USERNAME),
      'error'         => $error,
    ));
  }

但是,这并没有给出适当的结果:对于正确的用户名和密码,用户被重定向到welcome symfony页面 . 有没有人对此有解释?

我在symfony文档中发现我可以使用hiddden字段控制登录表单中的重定向,如下所示:

{# src/Acme/SecurityBundle/Resources/views/Security/login.html.twig #}
{% if error %}
    <div>{{ error.message }}</div>
{% endif %}

<form action="{{ path('login_check') }}" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="_username" value="{{ last_username }}" />

    <label for="password">Password:</label>
    <input type="password" id="password" name="_password" />

    <input type="hidden" name="_target_path" value="account" />

    <input type="submit" name="login" />
</form>

问题:我如何参数化路由以负责用户和管理员 .

1 回答

  • 2

    使用 _target_path 输入字段并将经过身份验证的用户定向到包含您的控制器的路由 . 在控制器内部,您可以检查用户的角色,并根据该角色转发给另一个控制器 .

相关问题