Facebook authorization with URL rewrite

214 Views Asked by At

i devoted whole day to this issue and can't solve it...could you help?

What is the problem

My facebook (and Google+) authorization does not work, if I have URL rewriting active.

How it bahaves

If I access FB (or G+) authorization page and agree with authorizaion, then I am redirected to my App and back to FB and again, and I receive:

This webpage has a redirect loop
ERR_TOO_MANY_REDIRECTS

How my Facebook auth class looks like

In my App I use this class for facebook login

<?php

namespace App\Presenters;

use Facebook\FacebookSession, 
    Facebook\FacebookRedirectLoginHelper, 
    Facebook\FacebookRequestException, 
    Facebook\GraphUser,
    Facebook\FacebookRequest;

class FacebookPresenter extends BasePresenter {

  /** @var \App\Model\UserManager @inject */
  public $um;

  /**
   * Default facebook action
   */
  public function actionDefault() {

    // Start session
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
    }

    // Configuration
    $appId = $this->context->parameters['facebook']['appId'];
    $appSecret = $this->context->parameters['facebook']['appSecret'];
    $scope = array('email');

    // This producs always valid route based on router configuration
    $loginRedirectUrl = $this->link('//Facebook:default');    

    FacebookSession::setDefaultApplication($appId, $appSecret);
    $helper = new FacebookRedirectLoginHelper($loginRedirectUrl);

    // Get facebook session
    try {
      $session = $helper->getSessionFromRedirect();
    } catch(FacebookRequestException $ex) {
     $this->redirectUrl($helper->getLoginUrl($scope));
    } catch(\Exception $ex) {
      $this->redirectUrl($helper->getLoginUrl($scope));
    }

    // Session was established
    if ($session) {
      try {
        $req = new FacebookRequest($session, 'GET', '/me');
        $userProfile = $req->execute()->getGraphObject(GraphUser::className());
        $fbArr = $userProfile->asArray();
        $fbId = $fbArr['id'];
        $fbArr['picture'] = "https://graph.facebook.com/$fbId/picture?width=360&height=360";

        // Login or register
        $this->loginOrRegister($fbId, $fbArr);

        // After facebook login redirect to homepage
        $this->flashMessage("Facebook login was successful", "success");
        $this->redirect('Homepage:');        
      } catch (FacebookRequestException $e) {
        $this->redirectUrl($helper->getLoginUrl($scope));
      }

    // Session was not established
    } else{
      $this->redirectUrl($helper->getLoginUrl($scope));
    }
  }

  /**
   * Login or registers user
   * @param String $fbId
   * @param array $fbArr
   */
  protected function loginOrRegister($fbId, $fbArr) {

    // Try to login with given ID
    try {

      // Login
      $this->user->login(NULL, NULL, $fbId, NULL);

      // Try to update user's picture
      if (isset($fbArr['picture']) && strlen($fbArr['picture']) > 0) {
        $this->um->updateAvatar($fbArr['picture'], $fbId, null);
      }

    } catch (\Nette\Security\AuthenticationException $ex) {

      // Retrieve social info
      $email = isset($fbArr['email']) ? $fbArr['email'] : "";
      $firstName = isset($fbArr['first_name']) ? $fbArr['first_name'] : "";
      $lastName = isset($fbArr['last_name']) ? $fbArr['last_name'] : "";
      $picture = isset($fbArr['picture']) ? $fbArr['picture'] : null;

      // Check if there is user with acquired email
      // If he/she is, then update his facebook ID and verify him/her and login
      $tmpUser = $this->createDao("AppUser")->loadByEmail($email);
      if ($tmpUser && $tmpUser->isPopulated()) {
        $tmpUser->updateFbId($fbId);
        $tmpUser->updateAvatar($picture, $fbId, null);
        $tmpUser->verify($tmpUser->getVCode());
        $this->user->login(NULL, NULL, $fbId, NULL);
      } else {

        // Send user to registration
        $this->redirect('Sign:register', array(
            'name' => ($firstName . " " . $lastName),
            'email' => $email, 
            'fbId' => $fbId)
        );
      }
    }
  }
}

How my router configuration looks like

If rewrite is false, then simple router is active and everything is working, otherwise not

  /**
   * @return \Nette\Application\IRouter
   */
  public static function createRouter() {

    $rewrite = true;

    // Simple router
    if (!$rewrite) {
      return new SimpleRouter('Homepage:default');
    }

    // Full router list
    $router = new RouteList();
    $router[] = new Route('', array(
        'presenter' => 'Homepage',
        'action' => 'default',
    ));
    $router[] = new Route('story', 'Homepage:story');
    $router[] = new Route('feed', 'Homepage:feed');
    $router[] = new Route('register', 'Sign:register');
    $router[] = new Route('verify', 'Sign:verify');
    $router[] = new Route('in', 'Sign:in');
    $router[] = new Route('user/<id>', 'User:default');
    $router[] = new Route('<presenter>/<action>[/<id>]', 'Homepage:default');
    return $router;
  }

How my URLs look like

For simple router:

https://www.facebook.com/v2.2/dialog/oauth?client_id=478905205596609&redirect_uri=http://localhost/~tester/testproject/www/?presenter=Facebook&state=4b63bfb3c9507c89347455663c2f5279&sdk=php-sdk-4.0.16&scope=email

For rewritten urls:

https://www.facebook.com/v2.2/dialog/oauth?client_id=478904678929995&redirect_uri=http://localhost/~tester/testproject/www/facebook/&state=536560378c582ddb17f0fe821cf20846&sdk=php-sdk-4.0.16&scope=email

UPDATE 2015-06-12

I found problematic part of code.... if URL rewrite is active, then

$session = $helper->getSessionFromRedirect();

is always null, so code always go to the last else in actionDefault. Of cause I've found this topic Why is getSessionFromRedirect() return a NULL? ... however, I call getSessionFromRedirect and getLoginUrl methods in right order

1

There are 1 best solutions below

0
On BEST ANSWER

This guy've made a package which may help you. There's also a class called FacebookAuthenticator, the main problem is that it has a lack of documentation, so you should just analyze the source code and get on with it.

Good Luck