使用Symfony 2.8和FOSUSerBundle 2.0,我试图:
我在security.yml中添加了target和default_target_path参数,但它只重定向到一条预定义路由:
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
login_path: fos_user_security_login
check_path: fos_user_security_check
csrf_token_generator: security.csrf.token_manager
default_target_path: fos_user_profile_show
always_use_default_target_path: false
logout:
path: fos_user_security_logout
target: fos_user_security_login
success_handler: app.logout_success_handler
anonymous: true
如您所见,我已经创建了logout_success_handler服务:
class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
protected $router;
public function __construct(Router $router)
{
$this->router = $router;
}
public function onLogoutSuccess(Request $request)
{
$route = $this->router->generate('my_route');
return new RedirectResponse($route);
}
}
但这是一个好方法吗? 如何添加flash消息?
此类服务的文件系统中的推荐位置是什么?我已将LogoutSuccessHandler
放在~/EventListener
目录中,但我认为这不是正确的地方......您的意见是什么?
此外,我还要在登录后准备类似的服务(重定向和flash消息)。
以下代码是否正常?
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\Session\Session;
class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
protected $router;
protected $session;
public function __construct(Router $router, Session $session)
{
$this->router = $router;
$this->session = $session;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token_name(token))
{
$this->session->getFlashBag()->add('success', 'user.welcome' );
$default_route = $this->router->generate('fos_user_profile_show');
return new RedirectResponse($default_route);
}
}
答案 0 :(得分:1)
这种方法是合适的。您可以使用以下方式添加flash message。
class LogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
protected $router;
protected $session;
public function __construct(Router $router, Session $session)
{
$this->router = $router;
$this->session = $session;
}
public function onLogoutSuccess(Request $request)
{
$this->session->getFlashBag()->add('success', 'user.logout');
$route = $this->router->generate('my_route');
return new RedirectResponse($route);
}
}