我只是希望管理员用户或前端用户即使在登录后也尝试访问登录页面
/admin/login (admin user)
或者
/login (front end user)
然后他们应该被重定向回他们的相关主页,比如/admin
或/
我只是希望管理员用户或前端用户即使在登录后也尝试访问登录页面
/admin/login (admin user)
或者
/login (front end user)
然后他们应该被重定向回他们的相关主页,比如/admin
或/
更简单的解决方案是将这两行添加到您的 app/config/security.yml 中:
always_use_default_target_path和default_target_path,例如:
firewalls:
main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_provider: form.csrf_provider
login_path: /login
check_path: /login_check
always_use_default_target_path: false
default_target_path: /your/start/path/
使用 LoginHandlers 在 Symfony2 中重定向登录/注销
当登录成功时,您应该实施AuthenticationSuccessHandlerInterface
处理最后一分钟的决定。
实现 AuthenticationSuccessHandlerInterface:
<?php
// AcmeBundle\Security\LoginSuccessHandler.php
namespace AcmeBundle\Security;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface {
protected $router;
protected $authorizationChecker;
public function __construct(Router $router, AuthorizationChecker $authorizationChecker) {
$this->router = $router;
$this->authorizationChecker = $authorizationChecker;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
$response = null;
if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
$response = new RedirectResponse($this->router->generate('backend'));
} else if ($this->authorizationChecker->isGranted('ROLE_USER')) {
$response = new RedirectResponse($this->router->generate('frontend'));
}
return $response;
}
}
将您的课程注册为服务:
# app/config/services.yml
services:
authentication.handler.login_success_handler:
class: AcmeBundle\Security\LoginSuccessHandler
arguments: ['@router', '@security.authorization_checker']
在防火墙中添加对 LoginSuccessHandler 类的引用
# app/config/security.yml
firewalls:
main:
pattern: ^/
form_login:
success_handler: authentication.handler.login_success_handler
您可以覆盖FOSUserBundle\Controller\SecurityController并在loginAction
.
use Symfony\Component\HttpFoundation\RedirectResponse;
// ...
public function loginAction(Request $request)
{
$authChecker = $this->container->get('security.authorization_checker');
$router = $this->container->get('router');
if ($authChecker->isGranted('ROLE_ADMIN')) {
return new RedirectResponse($router->generate('admin_home'), 307);
}
if ($authChecker->isGranted('ROLE_USER')) {
return new RedirectResponse($router->generate('user_home'), 307);
}
// ...
只需在您添加的页面的控制器中重定向 default_target_path
到所需的方向,例如,如果您输入 for default_target_path: /index
并且 index 是定义在 中的操作HomePageCOntroller
,请转到HomePageCOntroller
,测试当前用户是否为管理员:
if (($this->container->get('security.context')->isGranted('ROLE_ADMIN')))
然后将他重定向到管理空间。