2016-02-24 4 views
0

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

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

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

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

ответ

0

пожалуйста найти ниже 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, нормально запрос клиента маркер доступа от Google API и токенов доступа/разрешений/scope, вы можете восстановить все ожидаемые данные.

и ниже на стороне сервера управления (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); 
    } 

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

Смежные вопросы