在Laravel中,有一个简单的Auth::attempt(...
方法可用。我试图在Symfony中找到等价物。
我有一个已经实现AdvancedUserInterface
的学说用户实体。我一直在阅读Symfony安全文档,但我只想接受一个非常简单的POST请求,对会话的用户进行身份验证,并使用JSONResponse进行响应。
我缺少一个简单的方法吗?我是否需要编写某种自定义提供程序或...?
简短的回答是安装 FOSUserBundle 并使用他们的 LoginManager。在控制器中,您将需要一个如下所示的身份验证方法:
use Symfony'Component'HttpFoundation'Response;
use Symfony'Component'Security'Core'Exception'AccountStatusException;
use FOS'UserBundle'Model'UserInterface;
/**
* Authenticate a user with Symfony Security
*
* @param 'FOS'UserBundle'Model'UserInterface $user
* @param 'Symfony'Component'HttpFoundation'Response $response
*/
protected function authenticateUser(UserInterface $user, Response $response)
{
try {
$this->container->get('fos_user.security.login_manager')->loginUser(
$this->container->getParameter('fos_user.firewall_name'),
$user,
$response);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
}
长答案是自己构建一个精简版的 FOSUserbundle。
Laravel已经附带了2个UserProvider:Illuminate''Auth''DatabaseUserProvider和Illuminate''Auth''EloquentUserProvider。Symfony安全组件仅附带内存用户提供程序。这是有关如何执行此操作的秘诀:http://symfony.com/doc/current/cookbook/security/custom_provider.html。另外需要注意的是:因为你使用的是 Doctrine,所以你可以将 UserRepository 作为你的 UserProvider 类。
(可选,取决于您尝试执行的操作)在 app/config/security.yml 中定义新的防火墙
在控制器中,创建以下内容:
use Symfony'Component'Security'Core'User'UserInterface; use Symfony'Component'Security'Core'Authentication'Token'UsernamePasswordToken; protected function authenticateUser($firewallName, UserInterface $user) { $this->get('security.user_checker')->checkPostAuth($user); $token = new UsernamePasswordToken($user, null, $firewallName, $user->getRoles()); if ($this->container->isScopeActive('request')) { $this->get('security.authentication.session_strategy')->onAuthentication($this->container->get('request'), $token); } $this->get('security.context')->setToken($token); }
或者,您可能最好将其移动到身份验证服务提供商,并在控制器操作中调用此服务。
希望这有帮助。