3

ログイン成功後のカスタム ロールベース リダイレクト用のカスタム成功ログイン ハンドラがあります。

配列内のこれらの特別なロールのいずれ$specialRolesかが見つかると、新しいRedirectResponseが返されます。

/** @DI\Service("handler.login_sucess_handler") */
class LoginSuccessHandler implements uthenticationSuccessHandlerInterface
{
    private $router;
    private $securityContext;

    /**
     * @DI\InjectParams({
     *     "securityContext"= @DI\Inject("security.context"),
     *     "router"         = @DI\Inject("router") })
     */
    public function __construct(SecurityContext $securityContext,
        I18nRouter $router)
    {
        $this->securityContext = $securityContext;
        $this->router          = $router;
    }

    public function onAuthenticationSuccess(Request $request,
        TokenInterface $token)
    {
        $specialRoles = array('ROLE_1', 'ROLE_2', 'ROLE_3');

        foreach($specialRoles as $specialRole)
        {
            if($this->securityContext->isGranted($specialRole))
            {
                $redirectUrl = $this->router->generate('manage_index');
                return new RedirectResponse($redirectUrl);
            }
        }
    }
}

一方、ユーザーに特別なロールがない場合にどうなるかを指定する必要があります。/app/dashboardつまり、デフォルトルートをハードコーディングしないでください。つまり、ファイルdefault_target_pathから (ある場合) を読み取ります。security.yml

form_login:
    login_path:          /app/login
    check_path:          /app/login_check
    default_target_path: /app/dashboard
    success_handler:     handler.login_sucess_handler

これを行う方法はありますか?

もちろん、コードをそのままにしておくと、ユーザーが特別な役割を持っていない場合、例外がスローされます。

キャッチ可能な致命的なエラー: Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse() に渡される引数 1 は、Symfony\Component\HttpFoundation\Response のインスタンスでなければなりません。null を指定してください。

4

3 に答える 3

2

これは、私のプロジェクトの1つで行った方法です。

if ($targetPath = $request->getSession()->get('_security.target_path')) {
    return new RedirectResponse($targetPath);
}
于 2012-07-26T07:49:54.827 に答える
0

リダイレクトの問題は解決しましたか?これらのソリューションはまったく機能しませんでしたが、これは次のとおりです。

return new RedirectResponse($request->headers->get('Referer'));
于 2012-11-16T00:14:10.927 に答える
0

foreachループ後に必要なルートを含む return ステートメントを単純に追加してみませんか?

    public function onAuthenticationSuccess(
        Request $request, 
        TokenInterface $token
    )
    {
        $specialRoles = array('ROLE_1', 'ROLE_2', 'ROLE_3');

        foreach($specialRoles as $specialRole) {
            if ($this->securityContext->isGranted($specialRole)) {
                $redirectUrl = $this->router->generate('manage_index');
                return new RedirectResponse($redirectUrl);
            } 
        }

        $redirectUrl = $this->router->generate('your_custom_route');
        return new RedirectResponse($redirectUrl);
    }

もちろん、ルーティングでカスタム ルートを定義することを忘れないでください。

編集

_refererログインフォームに入力フィールドを設定してフォームとともに送信し、それを実行することもできます$request->get('_referer');

別の方法は、ヘッダーからリファラーを取得しようとすることです。$request->headers->get('Referer');

最後に、security.yml で定義されているデフォルトのターゲット パスを取得できます。$request->getSession()->get('_security.target_path');

于 2012-07-26T05:50:21.690 に答える