symfony 2 oauth protected api server to server

478 Views Asked by At

I'd want to create a set of API secured with Oauth2 protocol in Symfony 2.8.

OAuth server is implemented with FOSOAuthServerBundle and resides in the same server as API set.

Client Applications should communicate with API server through HWIOAuthBundle but They should do that on behalf of applications themselves, not third party users. In Google API this is called a 2 legs oauth authentication.

Obviously client applications can't send username and password data through a form, so I was wondering if it does exist a bundle or another method to expose oauth authentication for client applications logging in by themselves or I should simply extend HWIOAuthBundle Controller.

1

There are 1 best solutions below

0
On

Please find below AOuthentication method using js and an extended HWIOAuthBundle

 var googleAuth = function(){
            var googleUser = {};
            var gl_btn = $('#social_gl_auth');

            var startApp = function() {
                gapi.load('auth2', function(){
                    // Retrieve the singleton for the GoogleAuth library and set up the client.
                    auth2 = gapi.auth2.init({
                        client_id: 'xxxx.apps.googleusercontent.com',
                        cookiepolicy: 'single_host_origin',
                        // Request scopes in addition to 'profile' and 'email'
                        scope: 'email'
                    });
                    attachSignin(document.getElementById('social_gl_auth'));
                });
            };

            function attachSignin(element) {
                auth2.attachClickHandler(element, {},
                    function(googleUser) {
                        gl_oauthAttempt(googleUser);
                    }, function(error) {
                        alert(JSON.stringify(error, undefined, 2));
                    }
                );
            }

            // oauth of a known user
            function gl_oauthAttempt(authResponse){
                $.ajax({
                    url: Routing.generate('google_login'),
                    data: {
                        service: 'google',
                        authentication: authResponse
                    },
                    method: 'POST'
                }).done(function (response) {
                    if (response.hasOwnProperty('status')) {
                        if (response.status == 200) {
                            if (response.hasOwnProperty('target_path') &
                                response.target_path != null) {
                                window.location.href = response.target_path;
                            } else {
                                // reload page from server
                                window.location.reload(true);
                            }
                        }else{
                            // if user not registered trigger registration process
                            // with the same authResponse
                            if (response.status == 400) {
                                gl_oauthAttempt(authResponse);
                            }else{
                                console.log(reponse);
                            }
                        }
                    }
                });
            }

I don't know why do need password for OAuthentication process, normally client request an access token from google api and with access token / permissions /scope you can retrieve all expected data.

And below server side controller (HwiOAuthController / or custom Controller )

   /**
         * Handles OAuth user registration
         *
         * @param Request $request A request.
         *
         * @return JsonResponse
         *
         * @Method({"POST"})
         *
         * @Route("/connect", name="oauth_connect", options={"expose"=true})
         */
        public function connectAction(Request $request)
        {
            $this->debug('Start connect action');


            $serviceName = $request->request->get('service');
            if(!$serviceName) {
                $this->debug('Throw not found expection : service not found');
                throw new NotFoundHttpException('Service not found');
            }
            $this->debug('Redirect to connect service : '. $serviceName);
            return $this->forward('OAuthBundle:Connect:connectService', array('request' => $request, 'service' => $serviceName));
        }


        /**
         * Connects a user to a given account if the user is logged in and connect is enabled.
         *
         * @param Request $request The active request.
         * @param string $service Name of the resource owner to connect to.
         *
         * @return \Symfony\Component\HttpFoundation\Response
         * @throws \Exception
         *
         *
         * @throws NotFoundHttpException if `connect` functionality was not enabled
         * @throws AccessDeniedException if no user is authenticated
         *
         * @Route("/connect/service/{service}", name="connect_service")
         */
        public function connectServiceAction(Request $request, $service)
        {}
 /**
     * Handles OAuth user registration
     *
     * @param Request $request A request.
     *
     * @param String $service a service name.
     *
     * @return JsonResponse
     *
     * @Route("/registration/{service}", name="oauth_registration")
     */
    public function registrationAction(Request $request, $service)
    {
        $accessToken = $this->getTokenFromRequest($request);

        $resourceOwner = $this->getResourceOwnerByName($service);
        $this->debug('using access token :' . $
        $user = $this->get('oauth.helper')->buildOAuthUser($resourceOwner->getUserInformation($accessToken));

        $this->authenticateUser($user, $service, $accessToken);

        return new JsonResponse(array('message' => 'done' ,
            'status' => 200), 200);
    }

hope this helps you