我正在尝试将symfony2与facebook sdk集成。我知道已有一个很好的捆绑,但我想开发自己的机制。
以下是我解决这个问题的方法。在使用Facebook登录并授权我的应用程序后,facebook会重定向到我之前指定的网址。该url映射到此控制器的方法:
public function facebookLoginAction(Request $request) {
$facebook = $this->get("facebook");
$data = $facebook->api('/me', 'GET');
if ($data) {
$user = new AuthenticatedUser($data["name"], md5($data["id"]), "");
$token = new UsernamePasswordToken($user, $data["id"], 'secured_area', $user->getRoles());
$authToken = $this->get('security.authentication.manager')->authenticate($token);
$this->get('security.context')->setToken($authToken);
}
return new Response("<pre>" . print_r($token, true));
}
通过这样做,我试图强制用户登录,以便当他或她从Facebook回来时他已经全部排序了。
为了强制,这里是AuthenticatedUser
的代码:
namespace Nourdine\BasicBundle\Security\User;
use Symfony\Component\Security\Core\User\UserInterface;
class AuthenticatedUser implements UserInterface {
private $username;
private $password;
private $salt;
/**
* @param string $username
* @param string $password This md5-ied!
* @param string $salt The salt is empty at the mo!
*/
public function __construct($username, $password, $salt) {
$this->username = $username;
$this->password = $password;
$this->salt = $salt;
}
public function getRoles() {
return array("ROLE_USER");
}
public function getPassword() {
return $this->password;
}
/**
* @link http://symfony.com/doc/current/cookbook/security/custom_provider.html
* If getSalt() returns nothing, then the submitted password is simply encoded using the algorithm you specify in security.yml
*/
public function getSalt() {
return $this->salt; // this is empty indeed
}
public function getUsername() {
return $this->username;
}
public function eraseCredentials() {
}
public function equals(UserInterface $user) {
if (!$user instanceof WebserviceUser) {
return false;
}
if ($this->password !== $user->getPassword()) {
return false;
}
if ($this->getSalt() !== $user->getSalt()) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
}
因为我知道这很重要我想指出secured_area
是我防火墙的名字!这里:
<firewall name="secured_area" pattern="^/">
<anonymous />
<form-login login_path="/login" check_path="/login_check" />
<logout path="/logout" target="/" />
</firewall>
同样不是名为“facebook”且在控制器中使用的服务只不过是来自officla sdk的Facebook
类的实例。这是它在services.xml中的定义
<service id="facebook" class="Facebook">
<argument>%facebook.params%</argument>
</service>
有什么想法吗?我做错了什么?用户提供商的概念是否以某种方式涉及所有这些?即使登录实际上是强制的吗?
欢呼声