Symfony 2 защищенный oauth сервер API для сервера

Я хотел бы создать набор API, защищенный протоколом Oauth2 в Symfony 2.8.

Сервер OAuth реализован с помощью FOSOAuthServerBundle и находится на том же сервере, что и набор API.

Клиентские приложения должны взаимодействовать с сервером API через HWIOAuthBundle, но они должны делать это от имени самих приложений, а не сторонних пользователей. В API Google это называется двухсторонней аутентификацией oauth.

Очевидно, что клиентские приложения не могут отправлять данные имени пользователя и пароля через форму, поэтому мне было интересно, существует ли пакет или другой метод для предоставления аутентификации oauth для клиентских приложений, регистрирующихся самостоятельно, или я должен просто расширить контроллер HWIOAuthBundle.


person Matteo Rossi    schedule 24.02.2016    source источник


Ответы (1)


Ниже вы найдете метод AOuthentication с использованием js и расширенного 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);
                            }
                        }
                    }
                });
            }

Я не знаю, зачем нужен пароль для процесса OAuthentication, обычно клиент запрашивает токен доступа из API Google, и с токеном доступа/разрешениями/областью вы можете получить все ожидаемые данные.

И ниже контроллера на стороне сервера (HwiOAuthController/или пользовательский контроллер)

   /**
         * 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);
    }

надеюсь, это поможет вам

person CodeIsLife    schedule 24.02.2016