サーバーサイド アプリでの Google ログイン

<ph type="x-smartling-placeholder">

ユーザーがオフラインのときにユーザーの代わりに Google サービスを使用するには、 ユーザーがクライアント上でアプリを承認するハイブリッド サーバーサイド フローを使用する し、特別な 1 回限りの送信コードを 認証コードをサーバーに送信します。あなたのサーバーは、この 1 回限りの 独自のアクセス トークンと更新トークンを Google から取得して、サーバーが ユーザーがオフラインでも実行できる独自の API 呼び出しを実行できる。 この 1 回限りのコードフローには、純粋なサーバーサイドの サーバーにアクセス トークンを送信するという流れです。

サーバーサイドのアクセス トークンを取得するためのログインフロー 下に示します。

ワンタイム コードにはセキュリティ上の利点があります。コードを使用すると、 仲介を介さずにトークンをサーバーに直接提供します。 コードの漏洩はおすすめしませんが、コードの漏洩は非常に困難です。 クライアント シークレットは不要です。クライアント シークレットは控えておきましょう。

ワンタイム コード フローの実装

[Google ログイン] ボタンを使用すると、アクセス トークン認証コード。このコードはサーバーが交換できるワンタイム コードです。 Google のサーバーと通信して アクセストークンを取得します

次のサンプルコードは、 ワンタイムコード フローを実行します。

ワンタイム コード フローで Google ログインを認証するには、次のことを行う必要があります。

ステップ 1: クライアント ID とクライアント シークレットを作成する

クライアント ID とクライアント シークレットを作成するには、Google API Console プロジェクトを作成します。 OAuth クライアント ID を設定し、JavaScript 生成元を登録します。

  1. Google API コンソールに移動します。

  2. プロジェクトのプルダウンから、既存のプロジェクトを選択するか、新しいプロジェクトを作成します。 [新しいプロジェクトを作成] を選択します。

  3. サイドバーの [API と[認証情報] を選択して、 同意画面を設定する

    メールアドレスを選択し、プロダクト名を指定して、[Save] をクリックします。

  4. [認証情報] タブで、[認証情報を作成] プルダウンを選択します。 [OAuth クライアント ID] を選択します。

  5. [アプリケーションの種類] で、[ウェブ アプリケーション] を選択します。

    アプリが次にアクセスできるオリジンを登録します。 使用できます。送信元は、プロトコル、ポート、プロトコルの ホスト名、ポートです

    1. [承認済みの JavaScript 生成元] フィールドに、 説明します。複数のオリジンを入力して、アプリの実行を許可できます 異なるプロトコル、ドメイン、サブドメインを使用できます。ワイルドカードは使用できません。 以下の例で、2 番目の URL は本番環境の URL です。

      http://localhost:8080
      https://myproductionurl.example.com
      
    2. [承認済みのリダイレクト URI] フィールドに値は必要ありません。リダイレクト URI は、JavaScript API では使用されません。

    3. [作成] ボタンを押します。

  6. 表示される [OAuth クライアント] ダイアログ ボックスで、クライアント ID をコピーします。「 クライアント ID を使用すると、有効な Google API にアプリからアクセスできるようになります。

ステップ 2: Google プラットフォーム ライブラリをページに追加する

匿名関数を示す次のスクリプトを含めて、 この index.html ウェブページの DOM にスクリプトを挿入します。

<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
  <!-- BEGIN Pre-requisites -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
  </script>
  <script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
  </script>
  <!-- END Pre-requisites -->

ステップ 3: GoogleAuth オブジェクトを初期化する

auth2 ライブラリを読み込み、gapi.auth2.init() を呼び出して GoogleAuth オブジェクト。クライアント ID とリクエストするスコープを指定します init() を呼び出したとき。

<!-- Continuing the <head> section -->
  <script>
    function start() {
      gapi.load('auth2', function() {
        auth2 = gapi.auth2.init({
          client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
          // Scopes to request in addition to 'profile' and 'email'
          //scope: 'additional_scope'
        });
      });
    }
  </script>
</head>
<body>
  <!-- ... -->
</body>
</html>

ステップ 4: ページにログインボタンを追加する

ウェブページにログインボタンを追加し、 grantOfflineAccess() ワンタイムコードのフローを開始します。

<!-- Add where you want your sign-in button to render -->
<!-- Use an image that follows the branding guidelines in a real app -->
<button id="signinButton">Sign in with Google</button>
<script>
  $('#signinButton').click(function() {
    // signInCallback defined in step 6.
    auth2.grantOfflineAccess().then(signInCallback);
  });
</script>

ステップ 5: ユーザーをログインさせる

ユーザーがログインボタンをクリックして、アプリにこれらの権限へのアクセスを許可します。 ご確認ください。次に、 grantOfflineAccess().then() メソッドには、名前と値を含む JSON オブジェクトが 認証コード。例:

{"code":"4/yU4cQZTMnnMtetyFcIWNItG32eKxxxgXXX-Z4yyJJJo.4qHskT-UtugceFc0ZRONyF4z7U4UmAI"}

ステップ 6: 認証コードをサーバーに送信する

code は、サーバーが自身のサーバーと交換できるワンタイム コードです。 更新トークンの 2 つがあります更新トークンを取得できるのは、 オフライン アクセスを要求する認証ダイアログがユーザーに表示された。 select-account promptOfflineAccessOptions 手順 4 では、取得した更新トークンを後で使用するために保存する必要があります。 後続の交換では、更新トークンとして null が返されるためです。このフロー を使用すると、標準の OAuth 2.0 フローよりもセキュリティを強化できます。

アクセス トークンは常に有効な承認と引き換えに返される できます。

次のスクリプトは、ログインボタンのコールバック関数を定義します。日時 ログインが成功すると、この関数はクライアントサイドの ワンタイム コードを使用して、同じドメインのサーバーにワンタイム コードを送信します。

<!-- Last part of BODY element in file index.html -->
<script>
function signInCallback(authResult) {
  if (authResult['code']) {

    // Hide the sign-in button now that the user is authorized, for example:
    $('#signinButton').attr('style', 'display: none');

    // Send the code to the server
    $.ajax({
      type: 'POST',
      url: 'http://example.com/storeauthcode',
      // Always include an `X-Requested-With` header in every AJAX request,
      // to protect against CSRF attacks.
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      },
      contentType: 'application/octet-stream; charset=utf-8',
      success: function(result) {
        // Handle or verify the server response.
      },
      processData: false,
      data: authResult['code']
    });
  } else {
    // There was an error.
  }
}
</script>

ステップ 7: 認証コードをアクセス トークンに交換する

サーバーで、認証コードをアクセス トークンおよび更新トークンと交換します。こちらの ユーザーの代わりに Google API を呼び出すためのアクセス トークン。 更新トークンを使用して、アクセス トークンの有効期限が切れたときに新しいアクセス トークンを取得します。

プロフィールへのアクセスをリクエストした場合は、基本的な ID トークンも取得されます。 ユーザーのプロフィール情報を指定します。

次に例を示します。

Java
// (Receive authCode via HTTPS POST)


if (request.getHeader("X-Requested-With") == null) {
  // Without the `X-Requested-With` header, this request could be forged. Aborts.
}

// Set path to the Web application client_secret_*.json file you downloaded from the
// Google API Console: https://console.cloud.google.com/apis/credentials
// You can also find your Web application client ID and client secret from the
// console and specify them directly when you create the GoogleAuthorizationCodeTokenRequest
// object.
String CLIENT_SECRET_FILE = "/path/to/client_secret.json";

// Exchange auth code for access token
GoogleClientSecrets clientSecrets =
    GoogleClientSecrets.load(
        JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE));
GoogleTokenResponse tokenResponse =
          new GoogleAuthorizationCodeTokenRequest(
              new NetHttpTransport(),
              JacksonFactory.getDefaultInstance(),
              "https://oauth2.googleapis.com/token",
              clientSecrets.getDetails().getClientId(),
              clientSecrets.getDetails().getClientSecret(),
              authCode,
              REDIRECT_URI)  // Specify the same redirect URI that you use with your web
                             // app. If you don't have a web version of your app, you can
                             // specify an empty string.
              .execute();

String accessToken = tokenResponse.getAccessToken();

// Use access token to call API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Drive drive =
    new Drive.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), credential)
        .setApplicationName("Auth Code Exchange Demo")
        .build();
File file = drive.files().get("appfolder").execute();

// Get profile info from ID token
GoogleIdToken idToken = tokenResponse.parseIdToken();
GoogleIdToken.Payload payload = idToken.getPayload();
String userId = payload.getSubject();  // Use this value as a key to identify a user.
String email = payload.getEmail();
boolean emailVerified = Boolean.valueOf(payload.getEmailVerified());
String name = (String) payload.get("name");
String pictureUrl = (String) payload.get("picture");
String locale = (String) payload.get("locale");
String familyName = (String) payload.get("family_name");
String givenName = (String) payload.get("given_name");
Python
from apiclient import discovery
import httplib2
from oauth2client import client

# (Receive auth_code by HTTPS POST)


# If this request does not have `X-Requested-With` header, this could be a CSRF
if not request.headers.get('X-Requested-With'):
    abort(403)

# Set path to the Web application client_secret_*.json file you downloaded from the
# Google API Console: https://console.cloud.google.com/apis/credentials
CLIENT_SECRET_FILE = '/path/to/client_secret.json'

# Exchange auth code for access token, refresh token, and ID token
credentials = client.credentials_from_clientsecrets_and_code(
    CLIENT_SECRET_FILE,
    ['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
    auth_code)

# Call Google API
http_auth = credentials.authorize(httplib2.Http())
drive_service = discovery.build('drive', 'v3', http=http_auth)
appfolder = drive_service.files().get(fileId='appfolder').execute()

# Get profile info from ID token
userid = credentials.id_token['sub']
email = credentials.id_token['email']