development

서비스 애플리케이션 및 Google Analytics API V3 : 서버 간 OAuth2 인증?

big-blog 2020. 12. 4. 19:44
반응형

서비스 애플리케이션 및 Google Analytics API V3 : 서버 간 OAuth2 인증?


내 GA 계정에서 Google Analytics 데이터를 정기적으로 가져 오는 서버 응용 프로그램을 만들려고합니다. 내 데이터에 액세스하는 개인용 서버 측 애플리케이션입니다. 즉, 이 애플리케이션에 액세스하는 최종 사용자가 없습니다.

따라서 Google API 콘솔 에 내 애플리케이션을 서비스 애플리케이션 으로 등록 하여 클라이언트 ID비공개 키를 제공했습니다 . 이 서버 간 인증 흐름에는 최종 사용자가 없기 때문에 서비스 응용 프로그램은 응용 프로그램 비밀리디렉션 URL사용하지 않는다는 것을 알고 있습니다. 실제로 Google API 콘솔은 나에게 비밀을주지 않았고 리디렉션 URL을 요구하지 않았습니다.

안타깝게도 Google의 PHP 클라이언트 API 내에서 내 서비스 애플리케이션을 인증하는 방법을 알 수 없습니다 . 웹 응용 프로그램 인증에 대한 광범위한 문서가 최종 사용자는.

Google 문서에 따르면 비공개 키로 JWT 요청에 서명하여 서버 간 인증이 가능합니다 . PHP 클라이언트 API 내에서 수행하는 방법을 알아낼 수 없습니다 (소스를 탐색 했으며 개인 키로 요청에 서명하는 스크립트분명히 있지만 ).

여기에 뭔가 빠졌나요? 개인 키와 Google PHP 클라이언트 API를 사용하여 서비스 애플리케이션에 대한 인증을 수행하려면 어떻게해야합니까?

명확성을 위해 편집 됨


업데이트 2012 년 7 월 21 일

Google Analytics API V3는 이제 .p12 서명 JWT 요청에서 반환 된 OAuth2 토큰을 지원합니다. 즉, 이제 서비스 계정과 함께 Analytics API를 사용할 수 있습니다 .

현재 4 년 동안의 일일 지표 를 가져오고 있습니다.

다음은 빠른 'n'더러운 단계별입니다.

  1. Google API 콘솔로 이동하여 새 앱을 만듭니다.

  2. 에서 서비스 탭, 플립 Google 웹 로그 분석 스위치를

  3. 에서 API 액세스 탭을 클릭 OAuth2.0에 클라이언트 ID 만들기

    • 이름을 입력하고 로고를 업로드 한 후 다음을 클릭하십시오 .

    • 선택 서비스 계정 옵션을 누릅니다 클라이언트 ID 만들기

    • 개인 키 다운로드

  4. 이제 API 액세스 페이지로 돌아 왔습니다 . 클라이언트 ID이메일 주소 가있는 서비스 계정 이라는 섹션이 표시됩니다.

    • 이메일 주소 (예 : ####@developer.gserviceaccount.com )를 복사합니다.

    • 당신의 방문 GA 관리를 하고 당신의 재산에 대한 사용자로이 이메일을 추가

    • 이것은 필수입니다. 그렇지 않으면 암호 오류가 발생합니다.

  5. Github를 통해 최신 Google PHP 클라이언트 API 받기

    git submodule add https://github.com/google/google-api-php-client.git google-api-php-client-read-only
    
  6. 로큰롤 (업데이트 된 클래스 이름에 대한 팁에 감사드립니다) :

    // api dependencies
    require_once(PATH_TO_API . 'Google/Client.php');
    require_once(PATH_TO_API . 'Google/Service/Analytics.php');
    
    // create client object and set app name
    $client = new Google_Client();
    $client->setApplicationName(APP_NAME); // name of your app
    
    // set assertion credentials
    $client->setAssertionCredentials(
      new Google_Auth_AssertionCredentials(
    
        APP_EMAIL, // email you added to GA
    
        array('https://www.googleapis.com/auth/analytics.readonly'),
    
        file_get_contents(PATH_TO_PRIVATE_KEY_FILE)  // keyfile you downloaded
    
    ));
    
    // other settings
    $client->setClientId(CLIENT_ID);           // from API console
    $client->setAccessType('offline_access');  // this may be unnecessary?
    
    // create service and get data
    $service = new Google_Service_Analytics($client);
    $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
    

 

아래의 원래 해결 방법


모호한 문서에도 불구하고 대부분의 Google API는 아직 Google Analytics를 포함한 서비스 계정을 지원하지 않는 것 같습니다 . .p12 서명 JWT 요청에서 반환 된 OAuth2 토큰을 다이제스트 할 수 없습니다. 따라서 현재 로서는 서비스 계정으로 Google Analytics API V3를 사용할 수 없습니다 .

해결 방법 :

  1. 에서 구글 API 콘솔 하는 생성 클라이언트 응용 프로그램을.

  2. Follow the steps in the Google PHP Client API examples to generate a client_auth_url using your client_id, client_secret, and redirect_uri

  3. Login to Google using cURL. (Be sure to use a cookie file!)

  4. Open the client_auth_url in cURL and complete the form. Make sure you set curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); and curl_setopt($ch, CURLOPT_HEADER, 1); as the authorization_code will be in the Location: header of the response.

  5. Using your client_id, client_secret, redirect_uri, and the activation code from Step 4, post a request to the Google's OAuth2 Token machine. Make sure you include grant_type = "authorization_code" in your post fields.

  6. Hurray, you now have a refresh_token that never expires, and a working access_token! Post a request to the Google's OAuth2 Token machine with your client_id, client_secret, redirect_uri, and refresh_token when your access_token expires and you'll get a new one.


The Google API PHP Client now supports service accounts on trunk.

The implementation hasn't been released yet, so you'll need to checkout the latest version of the PHP client.

I've prepared a sample application that demonstrates how you can use service accounts to hit the Google Prediction API. To view the example, take a peek at examples/prediction/serviceAccount.php or visit: http://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php


If you are using Google's PHP client API then go to the Google API Console and click on API Access on the left.

Then Create a Client ID. That will give you the secret and it is where you set your redirect URL. It won't give you a redirect URL - that is the URL the app sends the user back to after authenticating.

There are other authentication methods you can look at.


you can use very usefull php library GAPI (Google Analytics API PHP Interface) to access Google Analytics without OAuth. It's easy to use.

참고URL : https://stackoverflow.com/questions/9863509/service-applications-and-google-analytics-api-v3-server-to-server-oauth2-authen

반응형