symfony2在controller中实现登陆以及登出

首先自己实现一个用户实体(实现 SymfonyComponentSecurityCoreUserUserInterface 中的方法),

1
2
3
4
5
6
7

use ComponentSecurityCoreUserUserInterface;

class UserEntity implements UserInterface
{

}

在 security.yml 定义Encoder(密码加密用)和Providers(验证令牌提供类),

1
2
3
4
5
6
7
8
9
10
11
12
security:
...
encoders:
DemoDemoBundleEntityUser: sha512
# ...

providers:
demo_login:
entity:
class: DemoDemoBundleEntityUser
property: account # 用户名property
# ...

登陆代码,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use ComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use ComponentSecurityCoreAuthenticationEvents;
use ComponentSecurityCoreEventAuthenticationEvent;


// $user是需要登陆的用户实体
// 产生令牌
$token = new UsernamePasswordToken($user, null, 'demo_login', $user->getRoles());
// 设置令牌
$this->get('security.token_storage')->setToken($token);
// 广播验证通过事件
$this->get('event_dispatcher')->dispatch(
AuthenticationEvents::AUTHENTICATION_SUCCESS,
new AuthenticationEvent($token)
);

登出代码,

1
2
$this->get('security.token_storage')->setToken(null);
$request->getSession()->invalidate();