0

我想在 Symfony 2.8 中创建一组使用 Oauth2 协议保护的 API。

OAuth 服务器使用 FOSOAuthServerBundle 实现,并与 API 集位于同一服务器中。

客户端应用程序应通过 HWIOAuthBundle 与 API 服务器通信,但它们应代表应用程序本身而不是第三方用户进行此操作。在 Google API 中,这称为 2 腿 oauth 身份验证。

显然客户端应用程序不能通过表单发送用户名和密码数据,所以我想知道它是否存在一个包或其他方法来为客户端应用程序自己登录公开 oauth 身份验证,或者我应该简单地扩展 HWIOAuthBundle 控制器。

4

1 回答 1

0

请在下面找到使用 js 和扩展 HWIOAuthBundle 的 AAuthentication 方法

 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 过程需要密码,通常客户端从 google api 请求访问令牌,并且使用访问令牌/权限/范围,您可以检索所有预期的数据。

在服务器端控制器(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);
    }

希望这对你有帮助

于 2016-02-24T23:51:53.803 回答