2014-11-10 2 views
2

나는 하루 종일이 문제를 처리해 왔으며 무엇이 잘못되었는지를 알 수 없습니다.javascript : Token이있는 Google Oauth 교차 클라이언트 인증이 만료되었습니다.

문제없이 작동하는 javascript 용 Google Api 클라이언트를 사용하는 애플리케이션이 있습니다. 이제 서버 측에서 무언가를하고 싶습니다. 조금 연구 한 결과 클라이언트 측에서 토큰을 사용하는 것이 백엔드에서 setAccessToken 메소드를 사용하는 것이 었습니다.

그래서 내가 JSON ( JSON.stringify(gapi.auth.getToken()) 사용)로 내 토큰 객체를 전송 시도하고 일단 내가 인증을 요구하는 백엔드 API 호출을 수행하려고, 나는 다음과 같은 오류 얻을 : 그래서, 조금 의아해

The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.

을 나는 다음과 같은

{ 
    "issued_to": "client_id", 
    "audience": "client_id", 
    "user_id": "user_id", 
    "scope": "https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me", 
    "expires_in": 1465, 
    "email": "user_email", 
    "verified_email": true, 
    "access_type": "online" 
} 

그래서 내가 토큰이 벌금과 유효 알고 반환 구글의 엔드 포인트에 토큰 사용하여 컬을 veryfing보십시오. 다음과 같이 내 코드가 설치되는 방식이다 (대한 편집 됨 :

<?php 
// The token JSON is not inline, it comes from another source directly from the client side, but this is how it looks 
$token_json = '{"state":"","access_token":"TOTALLY_VALID_ACCESS_TOKEN","token_type":"Bearer","expires_in":"3600","scope":"https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me","client_id":"CLIENT_ID","g_user_cookie_policy":"single_host_origin","cookie_policy":"single_host_origin","response_type":"token","issued_at":"1415583001","expires_at":"1415586601","g-oauth-window":{},"status":{"google_logged_in":false,"signed_in":true,"method":"PROMPT"}}'; 

$OAUTH2_CLIENT_ID = 'CLIENT_ID'; 
$OAUTH2_CLIENT_SECRET = 'CLIENT_SECRET'; 

$client = new Google_Client(); 
$client->setClientId($OAUTH2_CLIENT_ID); 
$client->setClientSecret($OAUTH2_CLIENT_SECRET); 
$client->setAccessToken($token_json); 

$youtube = new Google_Service_YouTube($client); 

try{ 

    /* Random code goes here */ 

    // Auth Exception here. 
    $insertRequest = $youtube->videos->insert("status,snippet", $video); 

} catch (Google_Exception $e) { 
    var_dump($e->getMessage()); 
} 

내가 오프라인 액세스 또는 뭔가를 설정해야합니까 나는 로그인 과정이 자바 스크립트에 있어야합니다 요구 사항의를 다시 너무 기회가? 백엔드에서 로그인 흐름

은 내가 부족 있나요

답변

3

음, 만약이에 다른 사람이 실수를 한단다 :.?

은 분명히, 공유가 다른 있기 때문에, 직접 토큰 갈 수있는 방법이 아니다

API 래퍼가 토큰을 다룬다. 와이. 당신이해야 할 것은 PHP에 한 번 코드를 전달하고 또한
$client = new Google_Client(); 
    $client->setClientId($OAUTH2_CLIENT_ID); 
    $client->setClientSecret($OAUTH2_CLIENT_SECRET); 

    // Couldn't find this anywhere in the docs, but it's required. If you don't pass this, you will get an Origin Mismatch error. 
    $client->setRedirectUri('postmessage'); 

    // Get this from javascript 
    $client->authenticate($ONE_TIME_CODE); 

    // Optionally, you might want to retrieve the token and save it somewhere else e.g. the session, as the code is only good for a single use.   
    $_SESSION['token'] = $client->getAccessToken(); 

토큰에 대한 액세스 권한을 획득하려면 다음을 사용하는 것입니다, JS에서 당신은 JS 토큰 외에이 일회성 코드를 필요로 지정해야 나는 다른 곳에서도 문서화 된 것을 찾을 수 없었다. gapi.auth.authorize에 대한

설정 예,

{ 
     client_id: CLIENT_ID 
     scope: APP_SCOPES 
     cookie_policy: 'single_host_origin' 
     response_type: 'code token' 
     immediate: true 
} 
+0

"postmessage"를 리디렉션 URL로 사용하면 중요한 정보였습니다. – tomasmcguinness

0

고마워, Moustached. 나는 또한 하루 종일 그것을 해결하려고 노력했다. 그러나, 나는 무엇을 한 번 코드는 어떻게 얻을 것을 명확하지 발견, 그래서 나는 경우 다른 사람의 얼굴에 여기에 같은 문제가 내 코드를 제공하기로 결정

<html> 
    <head> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
     <script src="https://apis.google.com/js/platform.js?onload=onGoogleAPILoad" async defer></script> 
     <script> 
      $(document).ready(function() { 
       var auth2; 

       window.onGoogleAPILoad = function() { 
        gapi.load('auth2', function() { 
         auth2 = gapi.auth2.init({ client_id: 'CLIENT_ID', scope: 'profile' }); 
        }); 
       }; 

       $('button').on('click', function() { 
        auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(function(response) { 
         $.ajax({ 
          method: 'POST', 
          url: '/auth/signin', 
          success: onAuthSuccess = function(response) { 
           // check response from your server and reload page if succeed 
          }, 
          data: { code: response.code } 
         }); 
        }); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <button>Sign In</button> 
    </body> 
</html> 

하고 코드를 백 엔드를 거의 같습니다 :

$client = new Google_Client(); 
$client->setClientId('CLIENT_ID'); 
$client->setClientSecret('CLIENT_SECRET'); 
$client->setRedirectUri('postmessage'); 

$client->authenticate($code); // here is one-time code 

$plus = new Google_Service_Plus($client); 
$user = $plus->people->get('me'); 
// $user is in array, containing now id, name, etc. 

여기에 해당 주제에 대한 article입니다.

관련 문제