为此,您必须添加一个 Grant Extensions,参见官方文档“Adding Grant Extensions”:https ://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/adding_grant_extensions.md
您可以找到我的 FacebookGrantExtension 以从 FB access_token 获取令牌:
class FacebookGrantExtension implements GrantExtensionInterface
{
protected $userManager = null;
protected $facebookSdk = null;
public function __construct(UserManager $userManager, \BaseFacebook $facebookSdk)
{
$this->userManager = $userManager;
$this->facebookSdk = $facebookSdk;
}
/**
* @see OAuth2\IOAuth2GrantExtension::checkGrantExtension
*/
public function checkGrantExtension(IOAuth2Client $client, array $inputData, array $authHeaders)
{
if (!isset($inputData['facebook_access_token'])) {
return false;
}
$this->facebookSdk->setAccessToken($inputData['facebook_access_token']);
try {
// Try to get the user with the facebook token from Open Graph
$fbData = $this->facebookSdk->api('/me');
if (empty($fbData) || !isset($fbData['id'])) {
return false;
}
// Check if a user match in database with the facebook id
$user = $this->userManager->findUserBy(array(
'facebookId' => $fbData['id']
));
// If no user found, register a new user and grant token
if (null === $user) {
return false;
}
// Else, return the access_token for the user
else {
return array(
'data' => $user
);
}
} catch(\FacebookApiExceptionion $e) {
return false;
}
}
}
和 config.yml :
my.oauth.facebook_extension:
class: My\CoreBundle\Oauth\FacebookGrantExtension
arguments:
userManager: "@fos_user.user_manager"
facebookSdk: "@fos_facebook.api"
tags:
- { name: fos_oauth_server.grant_extension, uri: 'http://grants.api.mywebsite.com/facebook_access_token' }