Skip to content

Instantly share code, notes, and snippets.

@mariselli
Last active May 25, 2018 09:43
Show Gist options
  • Save mariselli/162319987232b370018d to your computer and use it in GitHub Desktop.
Save mariselli/162319987232b370018d to your computer and use it in GitHub Desktop.
Facebook Grant Extensions in FOSOAuthServerBundle

Stackoverflow problem: http://stackoverflow.com/questions/18120632/fosoauthserverbundle-generate-manually-an-access-token

"Adding Grant Extensions" : https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/adding_grant_extensions.md

FacebookGrantExtension to get a token from a 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;
    }
}
}
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'  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment