我试图让奏鸣曲像这样工作:
- 如果普通用户登录,他将被重定向到“/”
- 如果管理员登录,他将被重定向到“/admin/dashboard”
我尝试使用 app/config/security.yml 中的防火墙来实现它,这就是我得出的结论:
# This firewall is used to handle the admin login area
# This part is handled by the Sonata User Bundle
admin:
pattern: /(.*)
context: user
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
failure_path: null
default_target_path: /admin/dashboard
logout:
path: /admin/logout
target: /
anonymous: true
# This firewall is used to handle the public login area
# This part is handled by the FOS User Bundle
main:
pattern: .*
context: user
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
failure_path: null
default_target_path: /
always_use_default_target_path: true
logout:
path: /logout
target: /
现在每个登录的用户都被重定向到/admin 显然为非管理员用户抛出“拒绝访问”。
有什么办法可以在这个 yml 文件中修复它,还是我应该寻找一些不同的方式来检查用户角色?
最佳答案
根据角色重定向用户的一种方法您可以实现自己的身份验证处理程序并在 onAuthenticationSuccess()
函数中检查用户的角色并根据用户的性质重定向
namespace YourNamespace\YourBundle\Services;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface {
protected $container;
public function __construct( $container ) {
$this->container = $container;
}
public function onAuthenticationSuccess( Request $request, TokenInterface $token ) {
$user = $token->getUser();
if($user->isGranted( 'ROLE_ADMIN' )){
$url = $this->container->get( 'router' )->generate( 'sonata_admin_dashboard' );
}else{
$url = $this->container->get( 'router' )->generate( 'your_welcome_route' );
}
return new RedirectResponse( $url );
}
}
为您的身份验证处理程序定义服务
services:
admin_success_handler:
class: YourNamespace\YourBundle\Services\AuthenticationHandler
arguments: [ '@service_container' ]
并在您的防火墙中定义
success_handler
admin:
pattern: /(.*)
context: user
form_login:
provider: fos_userbundle
login_path: /login
use_forward: false
check_path: /login_check
failure_path: null
default_target_path: /admin/dashboard
success_handler: admin_success_handler
logout:
path: /admin/logout
target: /
anonymous: true
关于sonata-admin - Sonata User Bundle + Admin Bundle 登录后管理员重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021600/