Partage

[Symfony 2] Api Rest (mobile) et FOSFacebookBundle

Le 16 février 2014 à 12:12:51

Bonjour, 

Je débute en symfony,  et je souhaite créer une application mobile en symfony.

L'utilisateur devra se connecter avec son compte facebook.

j'ai utilisé le bundle FOSFacebookBundle qui fonctionne bien en version web mais je bloque concernant la partie mobile.

J'ai suivi ces explications http://stackoverflow.com/questions/18645342/symfony-fosrestbundle-with-fosfacebookbundle

, mais j'ai une erreur 

Unrecognized options "api_facebook" under "security.firewalls.api"

Voici le contenu de mes differents fichiers

app/config/security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN

    providers:
        chainprovider:
            chain:
                providers: [fos_userbundle, my_fos_facebook_provider, mf_facebook_provider]       
        fos_userbundle:
            id: fos_user.user_provider.username
        my_fos_facebook_provider:
              id: my.facebook.user

    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    firewalls:
        api:
            pattern: ^/api
            api_facebook:
                provider: mf_facebook_provider
            stateless:  true
            anonymous: true
      
        main:
            pattern: ^/
            fos_facebook:
                app_url: ""
                server_url: "http://local:8080"
                login_path: /api/login
                check_path: /api/login_check
                default_target_path: /
                provider: my_fos_facebook_provider
            form_login:
                  provider: fos_userbundle
                  csrf_provider: form.csrf_provider
            logout:
                path: /logout
            anonymous: true



    access_control:
        
            - { path: ^/api/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/admin/, role: ROLE_ADMIN }
            # FOS facebook
            - { path: ^/secured/.*, role: [IS_AUTHENTICATED_FULLY] }
            - { path: ^/login_check, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/api/login_check, role: IS_AUTHENTICATED_ANONYMOUSLY }
            - { path: ^/.*, role: [IS_AUTHENTICATED_ANONYMOUSLY] }

app/config/config.yml

fos_facebook:
    alias:  facebook
    app_id: %api_facebook_id%
    secret: %api_facebook_secret%
    cookie: true
    permissions: [email, user_birthday,  user_interests, user_photos, user_likes, user_about_me,user_relationship_details, friends_about_me]
    
fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: MF\UserBundle\Entity\Profile  

services:
    my.facebook.user:
        class: MF\UserBundle\Security\User\Provider\FacebookProvider
        arguments:
            facebook: "@fos_facebook.api"
            userManager: "@fos_user.user_manager"
            validator: "@validator"
            container: "@service_container"    
            fields: [first_name, last_name, email, age_range, birthday, gender,interested_in, id, about, birthday,  gender, likes, photos, about,  age_range]
    api_facebook.security.authentication.listener:
        class: MF\UserBundle\Security\Firewall\ApiFacebookListener
        arguments: ['@security.context', '@security.authentication.manager', '@session', '']

\mf\UserBundle\DependencyInjection\Security\Factory\ApiFacebookFactory.php  

<?php
namespace MF\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 MF\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;
    }
}

mf\UserBundle\Security\Firewall\ApiFacebookListener.php

<?php
namespace MF\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));
        }
    }
}
  • mf\UserBundle\Resources\config\services.xml 
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <parameters>
        <parameter key="my_user.facebook_provider.class">MF\UserBundle\Security\User\Provider\FacebookProvider</parameter>
        <parameter key="mf_user.api_facebook.security.authentication.listener.class">MF\UserBundle\Security\Firewall\ApiFacebookListener</parameter>

    </parameters>
 
    <services>
        <!-- Facebook provider -->
        <service id="my_user.facebook_provider" class="%my_user.facebook_provider.class%">
            <argument type="service" id="fos_facebook.api" />
            <argument type="service" id="fos_user.user_manager" />
            <argument type="service" id="validator" />
            <argument type="service" id="service_container" />
            <argument>%fos_user.model.user.class%</argument>            
        </service>
        <service id="mf_user.api_facebook.security.authentication.listener" class="%mf_user.api_facebook.security.authentication.listener.class%">
            <argument type="service" id="session" />
            <argument type="service" id="security.authentication.manager" />
            <argument type="service" id="security.context" />
            <argument>%fos_user.model.user.class%</argument>            
        </service>        
    </services>
    




Pouvez-vous m'aiguillez svp et si vous avez un tuto pour les apis mobile/symfony et facebook , je suis preneuse.

Merci d'avance

-
Edité par leilanie le 17 février 2014 à 20:12:14

Publicité
Le 16 février 2014 à 12:12:51
Le 17 février 2014 à 8:19:11

Personne ne peut m'aider? :'(
Le 26 mars 2014 à 13:52:32

Yope,

Euh le message est clair pourtant. ton option api_facebook n'existe pas.

    firewalls:
        api:
            pattern: ^/api
            api_facebook:
                provider: mf_facebook_provider



Je ne fais pas du php, je fais du Sf.

[Symfony 2] Api Rest (mobile) et FOSFacebookBundle

× Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
  • Editeur
  • Markdown