3

我有一个 symfony 应用程序,它提供 RESTful API(用于移动应用程序)并具有后端管理。

我可以通过 facebook 成功登录到后端,但是我应该如何允许通过 RESTful API 登录?

4

2 回答 2

2

哇.. 差不多 12 小时后(!),这里是任何人都在寻找的解决方案:

  1. 我们需要创建新的自定义防火墙
  2. 这个工厂应该连接到 FOSFacebook 并验证令牌
  3. 如果它使用我们的新防火墙,它应该手动禁用任何会话或 cookie。
  4. 要使用防火墙,我们需要在每个请求中发送我们的令牌

编码

  • 首先定义我们的防火墙监听器

GoDisco/UserBundle/Security/Firewall/ApiFacebookListener.php

<?php
/**
 * Authored by  AlmogBaku
 *              almog.baku@gmail.com
 *              http://www.almogbaku.com/
 * 
 * 9/6/13 2:17 PM
 */

namespace Godisco\UserBundle\Security\Firewall;

use FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * API gateway through Facebook oAuth token: Firewall
 *
 * Class ApiFacebookListener
 * @package Godisco\UserBundle\Security\Firewall
 */
class ApiFacebookListener implements ListenerInterface
{
    /**
     * @var \Symfony\Component\Security\Core\SecurityContextInterface
     */
    protected $securityContext;

    /**
     * @var \Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface
     */
    protected $authenticationManager;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var string
     */
    protected $providerKey;

    public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, Session $session, $providerKey)
    {
        if (empty($providerKey)) {
            throw new \InvalidArgumentException('$providerKey must not be empty.');
        }

        $this->securityContext = $securityContext;
        $this->authenticationManager = $authenticationManager;
        $this->session = $session;
        $this->providerKey=$providerKey;
    }

    /**
     * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event.
     */
    public function handle(GetResponseEvent $event)
    {
        $accessToken    = $event->getRequest()->get('access_token');
        $token          = new FacebookUserToken($this->providerKey, '', array(), $accessToken);

        /**
         * force always sending token
         */
        $_COOKIE=array();
        $this->session->clear();


        try {
            if($accessToken)
                $returnValue = $this->authenticationManager->authenticate($token);
                $this->securityContext->setToken($returnValue);
            }
        } catch(AuthenticationException $exception) {
            if(!empty($accessToken))
                $event->setResponse(new Response(array("error"=>$exception->getMessage()),401));
        }
    }
}
  • 然后创建一个新的安全工厂来调用我们的监听器,并将身份验证连接到 FOSFacebookBundle。

GoDisco/UserBundle/DependencyInjection/Security/Factory/ApiFacebookFactory.php

<?php
/**
 * Authored by  AlmogBaku
 *              almog.baku@gmail.com
 *              http://www.almogbaku.com/
 * 
 * 9/6/13 2:31 PM
 */

namespace GoDisco\UserBundle\DependencyInjection\Security\Factory;

use FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;

/**
 * API gateway through Facebook oAuth token: Factory
 *
 * Class ApiFacebookFactory
 * @package GoDisco\UserBundle\DependencyInjection\Security\Factory
 */
class ApiFacebookFactory extends FacebookFactory
{
    /**
     * {@inheritdoc}
     */
    public function getKey()
    {
        return 'api_facebook';
    }

    /**
     * {@inheritdoc}
     */
    public function addConfiguration(NodeDefinition $node)
    {
        $builder = $node->children();
        $builder
            ->scalarNode('provider')->end()
            ->booleanNode('remember_me')->defaultFalse()->end()
        ;

        foreach ($this->options as $name => $default) {
            if (is_bool($default)) {
                $builder->booleanNode($name)->defaultValue($default);
            } else {
                $builder->scalarNode($name)->defaultValue($default);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createEntryPoint($container, $id, $config, $defaultEntryPointId)
    {
        return null;
    }

    /**
     * {@inheritdoc}
     */
    protected function createListener($container, $id, $config, $userProvider)
    {
        $listenerId = "api_facebook.security.authentication.listener";
        $listener = new DefinitionDecorator($listenerId);
        $listener->replaceArgument(3, $id);

        $listenerId .= '.'.$id;
        $container->setDefinition($listenerId, $listener);

        return $listenerId;
    }
}
  • 定义监听服务,这样我们就可以注入参数

GoDisco/UserBundle/Resources/config/services.yml

services:
    api_facebook.security.authentication.listener:
        class: GoDisco\UserBundle\Security\Firewall\ApiFacebookListener
        arguments: ['@security.context', '@security.authentication.manager', '@session', '']
  • 定义我们的新防火墙!

应用程序/配置/security.yml

security:
        api:
            pattern: ^/api
            api_facebook:
                provider: godisco_facebook_provider
            stateless:  true
            anonymous: true
        main:
            ...
于 2013-09-06T18:00:59.483 回答
0

您需要从您的客户端应用程序实施 oAuth 身份验证。

这是之前回答的:

如何轻松登录、Symfony2 Security、FOSUserBundle、FOSRestBundle?

于 2013-09-05T22:25:45.943 回答