我试图让奏鸣曲像这样工作:
- 如果普通用户登录,他被重定向到" /"
- 如果管理员登录,他将被重定向到" / 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文件中修复它,还是我会搜索一些检查用户角色的不同方法?
答案 0 :(得分:9)
根据角色重定向用户的一种方法是,您可以实现自己的身份验证处理程序,并在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