サーバーサイドの承認機能を実装する

Gmail API へのリクエストは、OAuth 2.0 認証情報を使用して承認する必要があります。ユーザーがオフラインの場合など、アプリケーションがユーザーに代わって Google API にアクセスする必要がある場合は、サーバーサイド フローを使用する必要があります。このアプローチでは、クライアントからサーバーに 1 回限りの認可コードを渡す必要があります。このコードは、サーバーのアクセス トークンと更新トークンの取得に使用されます。

サーバーサイドの Google OAuth 2.0 の実装の詳細については、ウェブサーバー アプリケーションに OAuth 2.0 を使用するをご覧ください。

目次

クライアント ID とクライアント シークレットを作成する

Gmail API を使用するには、まず設定ツールを使用する必要があります。このツールを使って、Google API Console でのプロジェクトの作成、API の有効化、認証情報の作成を指示に沿って行うことができます。

  1. [Credentials] ページで、[Create credentials] > [OAuth client ID] の順にクリックして OAuth 2.0 の認証情報を作成するか、[Create credentials] > [Service account key] の順にクリックしてサービス アカウントを作成します。
  2. OAuth クライアント ID を作成した場合は、アプリケーション タイプを選択します。
  3. フォームに記入し、[Create] をクリックします。

アプリケーションのクライアント ID とサービス アカウント キーが [Credentials] ページに表示されます。クライアント ID をクリックすると詳細を表示できます。パラメータは ID の種類によって異なりますが、メールアドレス、クライアント シークレット、JavaScript のオリジン(生成元)、リダイレクト URI などが含まれる場合があります。

後でコードに追加する必要があるため、クライアント ID をメモしておきます。

認可リクエストの処理

ユーザーが初めてアプリを読み込むと、リクエストされた権限スコープで Gmail アカウントにアクセスする権限をアプリに付与するためのダイアログが表示されます。この最初の承認の後、ユーザーに権限ダイアログが表示されるのは、アプリのクライアント ID が変更された場合、またはリクエストされたスコープが変更された場合のみです。

ユーザーを認証する

この最初のログインは、成功した場合に 認証コードを含む認証結果オブジェクトを返します。

認可コードをアクセス トークンと交換する

認証コードは、サーバーがアクセス トークンと交換できる 1 回限りのコードです。このアクセス トークンは Gmail API に渡され、アプリケーションにユーザーデータへのアクセス権が一定期間付与されます。

アプリに offline アクセスが必要な場合、アプリが初めて認可コードを交換すると、更新トークンも受け取ります。このトークンは、以前のトークンの有効期限が切れた後に新しいアクセス トークンを取得するために使用されます。アプリは、この更新トークンを(通常はサーバー上のデータベースに)保存して、後で使用します。

次のコードサンプルは、認可コードを offline アクセス権を持つアクセス トークンと交換し、更新トークンを保存する方法を示しています。

Python

CLIENTSECRETS_LOCATION の値は、client_secrets.json ファイルの場所に置き換えます。

import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...


# Path to client_secrets.json which should contain a JSON document such as:
#   {
#     "web": {
#       "client_id": "[[YOUR_CLIENT_ID]]",
#       "client_secret": "[[YOUR_CLIENT_SECRET]]",
#       "redirect_uris": [],
#       "auth_uri": "https://accounts.google.com/o/oauth2/auth",
#       "token_uri": "https://accounts.google.com/o/oauth2/token"
#     }
#   }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
    'https://www.googleapis.com/auth/gmail.readonly',
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
    # Add other requested scopes.
]

class GetCredentialsException(Exception):
  """Error raised when an error occurred while retrieving credentials.

  Attributes:
    authorization_url: Authorization URL to redirect the user to in order to
                       request offline access.
  """

  def __init__(self, authorization_url):
    """Construct a GetCredentialsException."""
    self.authorization_url = authorization_url


class CodeExchangeException(GetCredentialsException):
  """Error raised when a code exchange has failed."""


class NoRefreshTokenException(GetCredentialsException):
  """Error raised when no refresh token has been found."""


class NoUserIdException(Exception):
  """Error raised when no user ID could be retrieved."""


def get_stored_credentials(user_id):
  """Retrieved stored credentials for the provided user ID.

  Args:
    user_id: User's ID.
  Returns:
    Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To instantiate an OAuth2Credentials instance from a Json
  #       representation, use the oauth2client.client.Credentials.new_from_json
  #       class method.
  raise NotImplementedError()


def store_credentials(user_id, credentials):
  """Store OAuth 2.0 credentials in the application's database.

  This function stores the provided OAuth 2.0 credentials using the user ID as
  key.

  Args:
    user_id: User's ID.
    credentials: OAuth 2.0 credentials to store.
  Raises:
    NotImplemented: This function has not been implemented.
  """
  # TODO: Implement this function to work with your database.
  #       To retrieve a Json representation of the credentials instance, call the
  #       credentials.to_json() method.
  raise NotImplementedError()


def exchange_code(authorization_code):
  """Exchange an authorization code for OAuth 2.0 credentials.

  Args:
    authorization_code: Authorization code to exchange for OAuth 2.0
                        credentials.
  Returns:
    oauth2client.client.OAuth2Credentials instance.
  Raises:
    CodeExchangeException: an error occurred.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.redirect_uri = REDIRECT_URI
  try:
    credentials = flow.step2_exchange(authorization_code)
    return credentials
  except FlowExchangeError, error:
    logging.error('An error occurred: %s', error)
    raise CodeExchangeException(None)


def get_user_info(credentials):
  """Send a request to the UserInfo API to retrieve the user's information.

  Args:
    credentials: oauth2client.client.OAuth2Credentials instance to authorize the
                 request.
  Returns:
    User information as a dict.
  """
  user_info_service = build(
      serviceName='oauth2', version='v2',
      http=credentials.authorize(httplib2.Http()))
  user_info = None
  try:
    user_info = user_info_service.userinfo().get().execute()
  except errors.HttpError, e:
    logging.error('An error occurred: %s', e)
  if user_info and user_info.get('id'):
    return user_info
  else:
    raise NoUserIdException()


def get_authorization_url(email_address, state):
  """Retrieve the authorization URL.

  Args:
    email_address: User's e-mail address.
    state: State for the authorization URL.
  Returns:
    Authorization URL to redirect the user to.
  """
  flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
  flow.params['access_type'] = 'offline'
  flow.params['approval_prompt'] = 'force'
  flow.params['user_id'] = email_address
  flow.params['state'] = state
  return flow.step1_get_authorize_url(REDIRECT_URI)


def get_credentials(authorization_code, state):
  """Retrieve credentials using the provided authorization code.

  This function exchanges the authorization code for an access token and queries
  the UserInfo API to retrieve the user's e-mail address.
  If a refresh token has been retrieved along with an access token, it is stored
  in the application database using the user's e-mail address as key.
  If no refresh token has been retrieved, the function checks in the application
  database for one and returns it if found or raises a NoRefreshTokenException
  with the authorization URL to redirect the user to.

  Args:
    authorization_code: Authorization code to use to retrieve an access token.
    state: State to set to the authorization URL in case of error.
  Returns:
    oauth2client.client.OAuth2Credentials instance containing an access and
    refresh token.
  Raises:
    CodeExchangeError: Could not exchange the authorization code.
    NoRefreshTokenException: No refresh token could be retrieved from the
                             available sources.
  """
  email_address = ''
  try:
    credentials = exchange_code(authorization_code)
    user_info = get_user_info(credentials)
    email_address = user_info.get('email')
    user_id = user_info.get('id')
    if credentials.refresh_token is not None:
      store_credentials(user_id, credentials)
      return credentials
    else:
      credentials = get_stored_credentials(user_id)
      if credentials and credentials.refresh_token is not None:
        return credentials
  except CodeExchangeException, error:
    logging.error('An error occurred during code exchange.')
    # Drive apps should try to retrieve the user and credentials for the current
    # session.
    # If none is available, redirect the user to the authorization URL.
    error.authorization_url = get_authorization_url(email_address, state)
    raise error
  except NoUserIdException:
    logging.error('No user ID could be retrieved.')
  # No refresh token has been retrieved.
  authorization_url = get_authorization_url(email_address, state)
  raise NoRefreshTokenException(authorization_url)

保存された認証情報による承認

初回の認可フローが正常に完了した後にユーザーがアプリにアクセスすると、アプリケーションは保存された更新トークンを使用して、ユーザーに再度プロンプトを表示せずにリクエストを承認できます。

ユーザーの認証が完了している場合は、アプリはデータベースから更新トークンを取得し、サーバーサイド セッションにトークンを保存できます。更新トークンが取り消された場合や、無効な場合は、これをキャッチして適切な対応を行う必要があります。

OAuth 2.0 認証情報の使用

前のセクションで説明したように OAuth 2.0 認証情報を取得したら、それを使用して Gmail サービス オブジェクトを承認し、API にリクエストを送信できます。

サービス オブジェクトをインスタンス化する

このコードサンプルは、サービス オブジェクトをインスタンス化し、API リクエストを行うことを承認する方法を示しています。

Python
from apiclient.discovery import build
# ...

def build_service(credentials):
  """Build a Gmail service object.

  Args:
    credentials: OAuth 2.0 credentials.

  Returns:
    Gmail service object.
  """
  http = httplib2.Http()
  http = credentials.authorize(http)
  return build('gmail', 'v1', http=http)

承認済みリクエストを送信し、取り消された認証情報を確認する

次のコード スニペットは、承認済みの Gmail サービス インスタンスを使用してメールのリストを取得します。

エラーが発生すると、コードは HTTP 401 ステータス コードをチェックします。このコードは、ユーザーを認可 URL にリダイレクトすることで処理する必要があります。

Gmail API のその他のオペレーションについては、API リファレンスをご覧ください。

Python
from apiclient import errors
# ...

def ListMessages(service, user, query=''):
  """Gets a list of messages.

  Args:
    service: Authorized Gmail API service instance.
    user: The email address of the account.
    query: String used to filter messages returned.
           Eg.- 'label:UNREAD' for unread Messages only.

  Returns:
    List of messages that match the criteria of the query. Note that the
    returned list contains Message IDs, you must use get with the
    appropriate id to get the details of a Message.
  """
  try:
    response = service.users().messages().list(userId=user, q=query).execute()
    messages = response['messages']

    while 'nextPageToken' in response:
      page_token = response['nextPageToken']
      response = service.users().messages().list(userId=user, q=query,
                                         pageToken=page_token).execute()
      messages.extend(response['messages'])

    return messages
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    if error.resp.status == 401:
      # Credentials have been revoked.
      # TODO: Redirect the user to the authorization URL.
      raise NotImplementedError()

次のステップ

Gmail API リクエストの承認に問題がなければ、デベロッパー ガイドのセクションで説明されているように、メッセージ、スレッド、ラベルの処理を開始できます。

使用可能な API メソッドの詳細については、API リファレンスをご覧ください。