HWIOAuthBundle,如何使用Facebook访问令牌手动验证用户?

Syl*_*ain 8 authentication facebook symfony hwioauthbundle

我有一个网站(Symfony2)与HWIOauthBundle用于连接Facebook,一切正常.

现在,我正在尝试使用Cordova和Ionic框架(AngularJS)构建一个iOS应用程序,我想用Facebook验证我的用户:

  1. 使用$cordovaFacebook,我验证我的用户并获得有效的Facebook访问令牌,这没关系

  2. 我尝试使用此访问令牌在服务器端使用HWIOauthBundle对我的用户进行身份验证:

    GET http://..../login/facebook?code=MY_FACEBOOK_ACCESS_TOKEN
    
    Run Code Online (Sandbox Code Playgroud)
  3. Symfony用这个日志拒绝我的请求:

    INFO - Matched route "facebook_login" (parameters: "_route": "facebook_login")
    INFO - Authentication request failed: OAuth error: "Invalid verification code format."
    
    Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何通过Facebook连接在前端和后端验证我的用户?

谢谢 :)

tio*_*oit 3

我还想知道如何使用 HWIOAuthBundle 实现服务器端登录。我在网上没有找到任何解决方案,所以我根据我在网上读到的提示编写了功能。基本上,你必须:

  1. 在您的应用程序上对用户进行身份验证
  2. 使用 Facebook 令牌向您的服务器发出 http 请求。
  3. 在服务器端,检查令牌是否适用于您的 Facebook 应用程序,并检索用户的 Facebook ID。
  4. 根据获取的 ID 从数据库中获取您的用户。

这是我的 Symfony 控制器:

public function getSecurityFbAction($token)
{
    // Get the token's FB app info.
    @$tokenAppResp = file_get_contents('https://graph.facebook.com/app/?access_token='.$token);
    if (!$tokenAppResp) {
        throw new AccessDeniedHttpException('Bad credentials.');
    }

    // Make sure it's the correct app.
    $tokenApp = json_decode($tokenAppResp, true);
    if (!$tokenApp || !isset($tokenApp['id']) || $tokenApp['id'] != $this->container->getParameter('oauth.facebook.id')) {
        throw new AccessDeniedHttpException('Bad credentials.');
    }

    // Get the token's FB user info.
    @$tokenUserResp = file_get_contents('https://graph.facebook.com/me/?access_token='.$token);
    if (!$tokenUserResp) {
        throw new AccessDeniedHttpException('Bad credentials.');
    }

    // Try to fetch user by it's token ID, create it otherwise.
    $tokenUser = json_decode($tokenUserResp, true);
    if (!$tokenUser || !isset($tokenUser['id'])) {
        throw new AccessDeniedHttpException('Bad credentials.');
    }
    $userManager = $this->get('fos_user.user_manager');
    $user = $userManager->findUserBy(array('facebookId' => $tokenUser['id']));

    if (!$user) {
        // Create user and store its facebookID.
    }

    // Return the user's JSON web token for future app<->server communications.
}
Run Code Online (Sandbox Code Playgroud)

我抛出 Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException 异常来处理我的应用程序上的登录错误。

当然,您确实应该使用 https,因为您将交换敏感信息。

我不知道这是否是最好的方法,但效果很好。希望能帮助到你 !