I am writing Guards to handle OAuth for my Symfony 3 application.
As part of it, in one of my services, I need to generate an absolute URL to send to Twitter as the Callback URL.
#services.yml
...
app.twitter_client:
class: MyApiBundle\Services\TwitterClient
arguments:
- %twitter_client_id%
- %twitter_client_secret%
- connect_twitter_check
- '@request_stack'
- '@router'
- '@logger'
app.twitter_authenticator:
class: MyApiBundle\Security\TwitterAuthenticator
arguments:
- '@app.twitter_client'
- '@logger'
The logger is temporary for debugging.
#TwitterClient.php service
...
use Monolog\Logger;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
class TwitterClient
{
/**
* TwitterClient constructor.
* @param string $identifier
* @param string $secret
* @param string $callbackUrl
* @param RequestStack $requestStack
* @param RouterInterface $router
* @param Logger $logger
*/
public function __construct(
string $identifier,
string $secret,
string $callbackUrl,
RequestStack $requestStack,
RouterInterface $router,
Logger $logger
) {
$callbackUrl = $router->generate($callbackUrl, [], RouterInterface::ABSOLUTE_URL);
$logger->info($callbackUrl);
...
}
And when it outputs the $callbackUrl
to the logs, it just says localhost, even though I am accessing it using a different URL.
http://localhost/connect/twitter/check
But if I do the same from my a controller, it outputs the full proper URL.
#TwitterController.php
...
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
class TwitterController extends Controller
{
/**
* @Route("/connect/twitter")
* @return RedirectResponse
*/
public function connectAction()
{
/** @var RouterInterface $router */
$router = $this->container->get('router');
$callbackUrl = $router->generate('connect_twitter_check', [], RouterInterface::ABSOLUTE_URL);
/** @var Logger $logger */
$logger = $this->container->get('logger');
$this->container->get('logger')
->info($callbackUrl);
...
This outputs:
https://dev.myapi.com:8082/app_dev.php/connect/twitter/check
The dev.myapi.com
domain is set up in my hosts file and points to localhost, to make it easier to differentiate between my local apps and also to make it easier to integrate with OAuth services.