I am trying to implement facebook login for a web-app. Here is the FacebookConnect.php
<?php
namespace Vendor\GiftBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Generator\UrlGenerator;
class FacebookConnectController extends Controller
{
/**
* @Route("/connect/facebook", name="connect_facebook")
*/
public function connectFacebookAction(Request $request)
{
// redirect to Facebook
$redir = $this->generateUrl('connect_facebook_check', array(), UrlGeneratorInterface::ABSOLUTE_URL);
$facebookOAuthProvider = $this->get('app.facebook_provider');
$url = $facebookOAuthProvider->getAuthorizationUrl([
// these are actually the default scopes
'scopes' => ['public_profile', 'email'],
'redirect_uri' => [$redir],
]);
return $this->redirect($url);
}
/**
* @Route("/connect/facebook-check", name="connect_facebook_check")
*/
public function connectFacebookActionCheck()
{
// will not be reached!
}
}
When I hit the button which triggers the connectFacebookAction function I get the FB Error The redirect_uri URL must be absolute. It's like it ignores the absolute URL I have given him in the parameters.
What am I doing wrong?
EDIT: Is the authorization URL changing in any circumstances or remains the same for the app? Could I just hardcode it in until I figure out how to fix this?
EDIT2: I figured out why the URL is relative and not absolute. Here is my services configuration:
services:
app.facebook_provider:
class: League\OAuth2\Client\Provider\Facebook
arguments:
-
clientId: %facebook_app_id%
clientSecret: %facebook_app_secret%
graphApiVersion: v2.8
redirectUri: "@=service('router').generate('connect_facebook_check', {}, true)"
How do I do an absolute URL generation from a route in services?
Are you using version 1.x of league/oauth2-client (you can check in composer.lock)? That ignores the redirect_uri in getAuthorizationUrl and uses the one you pass in the constructor. If you're using that version, change the definition for app.facebook_provider to read
Note the 0 instead of true. The UrlGeneratorInterface constants have changed in 2.8.
I think your problem is that you're missing the request context in your service. Have a look at: http://symfony.com/doc/current/console/request_context.html
You could pass it the request and then do something like: