2013-07-11 1 views
1

gapi.auth.authorize를 통해 OAuth 2.0을 사용하여 Google 사용자를 인증하고 gapi.client.request를 통해 Google Fusion Tables sqlGet 쿼리를 실행하는 페이지를 작성하고 있습니다. 내 쿼리가 인증 전에 제대로 실행되지만 인증 후 을 30 초 이상 실행하면 403 "Insufficient Permission"오류로 실패합니다.gapi.auth를 통해 Google+ 로그인 후에 Google Fusion Tables sqlGet 쿼리가 작동하지 않는 이유는 무엇입니까?

문제는이 페이지에 설명된다 :

  1. 클릭 "쿼리"구글 퓨전 테이블 반환 쿼리를 SQL은-얻을 gapi.client.request를 실행하려면 : https://googledrive.com/host/0B5Urq1jZb1MYSWloU3NTY2M4Qnc/test3b.htm

    다음 단계를 수행하십시오 행수. 2 단계와 3 단계에서 OAuth를 사용할 때까지 성공적으로 실행됩니다.

  2. "OAuth 시작"을 클릭하면 Google+에 대한 즉각적인 승인이 실행됩니다. 현재 Google+에 로그인 한 경우 사용자 이름과 ID가 세 번째 버튼에 표시됩니다.

  3. Google+ 사용자 이름이 세 번째 버튼에 표시되지 않으면 버튼 ('인증')을 클릭하고 Google+에 로그인하십시오.

  4. "검색어"버튼을 다시 클릭하십시오. OAuth 승인 후 약 30 초 이내에 쿼리를 누르면 오류없이 실행됩니다. 그 후에 쿼리가 403 오류와 함께 실패합니다. 왜?

    <!DOCTYPE html> 
    <html> 
    <head> 
        <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0, maximum-scale=1.0" /> 
    
        <title>Test3b</title> 
    
        <style type="text/css"> 
        </style> 
    
        <script src="scripts/jquery-1.10.2.min.js" type="text/javascript"></script> 
    
        <script type="text/javascript"> 
         var g_domIsReady = false; 
         var g_gapiIsReady = false; 
    
         $(function() { 
          log("@$(function())"); 
          g_domIsReady = true; 
          start(); 
         }); 
    
         function gapiIsReady() { 
          log("@gapiIsReady"); 
          g_gapiIsReady = true; 
          start(); 
         } 
    
         function start() { 
    
          // Make sure both the gapi.client and the DOM (per jquery) are ready. 
    
          if (!(g_gapiIsReady && g_domIsReady)) return; 
    
          // Define members. 
    
          log("@start - gapi and DOM are ready"); 
    
          var m_apiKey = "AIzaSyAvb0NHQMwyPbMJRtz2zRL4wTiVjZDiois"; // Points to Google account (including Google Drive) at [email protected]eodesy.net. 
          var m_clientId = "868768273487-q295tdfr54uvo98v74891qakcr9ci0pf.apps.googleusercontent.com"; 
          var m_scopes = "https://www.googleapis.com/auth/plus.me"; 
    
          // Wire buttons. 
    
          var queryButton = document.getElementById('query-button'); 
          queryButton.onclick = function() { runGetRequest(); return false; }; 
          var startOAuthButton = document.getElementById('startOAuth-button'); 
          startOAuthButton.onclick = function() { startOAuth(); return false; }; 
    
          // Set-up the gapi. 
    
          gapi.client.setApiKey(m_apiKey); 
    
          //---------------------------------------------------------------------------- 
          // gapi.client.request query functions. 
          //---------------------------------------------------------------------------- 
    
          function runGetRequest() { 
           log("@runGetRequest"); 
           var tableId = "1VZgvKyuh9uHXkQawpxg1MU8AlO8Mngl-sx7SP74"; // TR_TREE_E 
           var sql = "select count(GID) from " + tableId + " where GID > 50000"; 
           var path = "/fusiontables/v1/query"; 
           var restRequest = gapi.client.request({ 
            path: path, 
            params: { 'sql': sql } 
           }); 
           restRequest.execute(jsonCallback); 
          } 
    
          function jsonCallback(json) { 
           log("@jsonCallback"); 
           var output = JSON.stringify(json); 
           log(output); 
           alert(output); 
          } 
    
          //---------------------------------------------------------------------------- 
          // OAuth functions. 
          //---------------------------------------------------------------------------- 
    
          function startOAuth() { 
    
           log("@startOAuth"); 
    
           var authorizeButton = document.getElementById('authorize-button'); 
           window.setTimeout(checkAuth, 1); // check auth in 1 ms 
    
           function checkAuth() { 
            log("@checkAuth"); 
            gapi.auth.authorize({ 
             client_id: m_clientId, 
             scope: m_scopes, 
             immediate: true 
            }, handleAuthResult); 
           } 
    
           function handleAuthResult(authResult) { 
            log("@handleAuthResult"); 
            if (authResult && !authResult.error) { 
             log("@handleAuthResult - authResult=true"); 
             log(authResult); // authResult is a token (with 3600 second expiration). 
             authorizeButton.disabled = true; 
             useAuthResults(); 
            } else { 
             log("@handleAuthResult - authResult=false"); 
             authorizeButton.disabled = false; 
             authorizeButton.onclick = handleAuthClick; 
            } 
           } 
    
           function handleAuthClick() { 
            log("@handleAuthClick"); 
            gapi.auth.authorize({ 
             client_id: m_clientId, 
             scope: m_scopes, 
             immediate: false 
            }, handleAuthResult); 
            return false; 
           } 
    
           function useAuthResults() { 
            log("@useAuthResults"); 
            // Get the Google+ user's ID and name (member info). 
            gapi.client.load('plus', 'v1', function() { 
             log("@gapi.client.load callback"); 
             var request = gapi.client.plus.people.get({ 'userId': 'me' }); 
             request.execute(function (aInfo) { 
              log("@request.execute callback"); 
              if (aInfo.code !== undefined) { 
               alert('Google+ API returned ' + aInfo.code + ': ' + aInfo.message); 
              } else { 
               // Here with successful sign-in. Display the user name. 
               log('Google+ user id, name: ' + aInfo.id + ', ' + aInfo.displayName); 
               authorizeButton.value = aInfo.displayName + " +" + aInfo.id; 
              } 
             }); 
            }); 
           } 
    
          } 
         } 
    
         function log(msg) { 
          if (console) console.log(msg); 
         } 
        </script> 
    
        <script src="https://apis.google.com/js/client.js?onload=gapiIsReady" type="text/javascript"></script> 
    
    </head> 
    
    <body> 
        <h1>Test3a</h1> 
        <p>This pages demonstrates a problem I am having using gapi.client.request with gapi.auth.</p> 
    
        <input type="button" id="query-button" value="Query"><br> 
        <input type="button" id="startOAuth-button" value="Start OAuth"><br> 
        <input type="button" id="authorize-button" value="Authorize"><br> 
    
        <p>Steps...</p> 
        <p>1. Click "Query" to run a gapi.client.request Google Fusion Table SQL-get query returning 
        a count of rows. This will run successfully until OAuth is used in steps 2 and 3.</p> 
        <p>2. Click "Start OAuth" to run an immediate:true authorization against Google+. If you 
        are currently signed into Google+, your user name will be displayed in the third button.</p> 
        <p>3. If your Google+ user name is not displayed in the third button, press it ("Authorize") 
        and sign into Google+.</p> 
        <p>4. Click the "Query" button again. 
        The query will run without error when pressed within about 30 seconds of OAuth authorization. 
        After that, the query fails with a 403 error. WHY?</p> 
    </body> 
    
    </html> 
    

    나는 퓨전 테이블 쿼리를 사용하려면 로그인에서 사용자가 페이지 사용 세부 사항을 추적 아닌 Google+를 사용하려는 있습니다 : 여기

는 데모 페이지에 대한 소스입니다 .

저는 OAuth와 gapi.client.request를 처음 접합니다. 그래서 제 부분에 대한 간단한 오해 일 수 있습니다.
통찰력을 주셔서 감사합니다.

답변

0

나는 당신에 대한 모든 해답을 가지고 있지 않지만, 여기에 내가 생각하는 데 도움이 될 수 있습니다 그 일부입니다 :

  1. 당신은 G +의 gapi.client.request 객체와 사용자 로그인을해야하기 전에 각 요청에 "key = yourAPIKey"매개 변수를 추가합니다. 당신은 G +와 사용자 로그인을 설정 한 후

  2. 의 gapi.client.request 객체는 가 전송하는 각 요청에 "키 = yourAPIKey"매개 변수를 추가하고 "권한 부여 : 무기명은 ya.xxxxxx"헤더를 로그인 한 사용자의 액세스 토큰을 나타내는 각각의 요청으로.

나는 액세스 토큰이 서버로 전송되고 있기 때문에 당신이 403을보고있는 이유는 생각하지만, 토큰하지 않습니다 FusionTables 데이터에 액세스 권한을 부여하는 범위가 포함됩니다. 액세스 토큰이 전송되지 않으면이 유효성 검사가 수행되지 않습니다.

실제로 사용자가 소유 한 데이터에 액세스하려는 경우 사용자가 gapi.auth.authorize 호출에 적절한 범위를 포함하여 응용 프로그램에 데이터 액세스 권한을 부여하는 데 동의해야합니다 (예 : "https://www.googleapis.com/auth/fusiontables").

그러나 특정 사용자를 대신하여 데이터에 액세스하려고 생각하지 않으므로 내가 실제로하고 싶다고 생각하는 것은 퓨전 테이블 API를 호출하는 동안 "권한 부여"헤더가 전혀 전송되지 않도록하는 것입니다. .

사용자가 로그인 할 때 gapi.client.request 라이브러리가 해당 헤더를 보내지 못하도록하는 쉬운 방법이 보이지 않으므로 대체 해결책은 gapi.client를 사용하지 않고 HTTP 객체를 만드는 것입니다 .request 라이브러리 (예 : XMLHttpRequest를 직접 사용) - 각 요청에 "key = yourAPIKey"를 수동으로 포함하십시오.

(설명 할 수없는 것은 30 초 동안 다른 행동이 나타나는 이유입니다 ...)

+0

감사합니다. aeijdenberg. 맞습니다. 제 페이지는 사용자의 융합 표에 액세스 할 필요가 없으므로 그 허가를 요청하지 않아야합니다. 나는 gapi.client.request 호출 대신 jQuery $ .ajax() XHR 호출을 사용하여 시도했지만 그 작업을 수행 할뿐만 아니라 어떻게 든 gapi.client에 대한 오류없는 작업의 또 다른 ~ 30 초 창을 엽니 다. 요청 쿼리! 하지만 $ .ajax()는 FT SQL POST 작업 중에 IE8 및 IE9에서 CORS 문제가있는 것으로 보입니다. 아마도 gapi.client.request 쿼리에 대한 희망을 포기하고 내 $ .ajax() 문제를 해결할 방법을 찾아야 할 것입니다. – user2055849