Wdróż autoryzację po stronie serwera

Żądania wysyłane do interfejsu Gmail API muszą być autoryzowane za pomocą danych logowania OAuth 2.0. Przepływ po stronie serwera należy stosować, gdy aplikacja musi uzyskiwać dostęp do interfejsów API Google w imieniu użytkownika, np. gdy użytkownik jest offline. To podejście wymaga przekazania jednorazowego kodu autoryzacji z klienta na serwer. Ten kod służy do uzyskania tokena dostępu i tokenów odświeżania dla serwera.

Więcej informacji o implementacji protokołu OAuth 2.0 Google po stronie serwera znajdziesz w artykule Używanie OAuth 2.0 w aplikacjach udostępnianych przez serwer WWW.

Spis treści

Tworzenie identyfikatora klienta i tajnego klucza klienta

Aby rozpocząć korzystanie z interfejsu Gmail API, musisz najpierw użyć narzędzia do konfiguracji, które przeprowadzi Cię przez proces tworzenia projektu w Konsoli interfejsów API Google, włączania interfejsu API i tworzenia danych logowania.

  1. Na stronie Dane logowania kliknij Utwórz dane logowania > Identyfikator klienta OAuth, aby utworzyć dane logowania OAuth 2.0, lub Utwórz dane logowania > Klucz konta usługi, aby utworzyć konto usługi.
  2. Jeśli masz utworzony identyfikator klienta OAuth, wybierz typ aplikacji.
  3. Wypełnij formularz i kliknij Utwórz.

Identyfikatory klienta aplikacji i klucze konta usługi są teraz widoczne na stronie Dane logowania. Aby uzyskać szczegółowe informacje, kliknij identyfikator klienta. Parametry różnią się w zależności od typu identyfikatora, ale mogą obejmować adres e-mail, tajny klucz klienta, źródła JavaScriptu lub identyfikatory URI przekierowania.

Zanotuj identyfikator klienta, ponieważ będziesz musiał/a dodać go później do kodu.

Obsługa próśb o autoryzację

Gdy użytkownik po raz pierwszy wczytuje Twoją aplikację, wyświetla się okno dialogowe z prośbą o przyznanie aplikacji uprawnień dostępu do jego konta Gmail w zakresie zakresów uprawnień. Po tej wstępnej autoryzacji okno uprawnień będzie wyświetlane użytkownikowi tylko wtedy, gdy zmieni się identyfikator klienta aplikacji lub zakresy, o które prosi aplikacja.

Uwierzytelnianie użytkownika

Początkowe logowanie zwraca obiekt wyniku autoryzacji, który w przypadku powodzenia zawiera kod autoryzacji.

Wymiana kodu autoryzacji na token dostępu

Kod autoryzacji to jednorazowy kod, który serwer może wymienić na token dostępu. Ten token dostępu jest przekazywany do interfejsu Gmail API, aby przyznać aplikacji dostęp do danych użytkownika na ograniczony czas.

Jeśli Twoja aplikacja wymaga dostępu offline, przy pierwszej wymianie kodu autoryzacji otrzymuje też token odświeżania, którego używa do uzyskiwania nowego tokena dostępu po wygaśnięciu poprzedniego. Aplikacja przechowuje ten token odświeżania (zwykle w bazie danych na serwerze) do późniejszego wykorzystania.

Poniższe przykłady kodu pokazują, jak wymienić kod autoryzacji na token dostępu z dostępem offline i zapisać token odświeżania.

Python

Zastąp wartość CLIENTSECRETS_LOCATION lokalizacją pliku credentials.json.

import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import Credentials # Needed for type hinting/usage in comments
from googleapiclient.discovery import build
from googleapiclient import errors as google_api_errors
import httplib2

# Path to credentials.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."""
    super().__init__(f"Authorization URL: {authorization_url}")
    self.authorization_url = authorization_url

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

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

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

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:
    NotImplementedError: 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. (oauth2client.client.Credentials needs to be imported)
  #       Example:
  #       from oauth2client.client import Credentials
  #       json_creds = load_from_db(user_id)
  #       if json_creds:
  #           return Credentials.new_from_json(json_creds)
  #       return None
  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:
    NotImplementedError: 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.
  #       Example:
  #       save_to_db(user_id, credentials.to_json())
  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 as 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 google_api_errors.HttpError as 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
  # The step1_get_authorize_url method uses the flow.redirect_uri attribute.
  flow.redirect_uri = REDIRECT_URI
  return flow.step1_get_authorize_url()

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) # Can raise NoUserIdException or google_api_errors.HttpError
    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 as 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)

Autoryzacja za pomocą zapisanych danych logowania

Gdy użytkownicy odwiedzą Twoją aplikację po pomyślnym przejściu procesu autoryzacji po raz pierwszy, aplikacja może użyć zapisanego tokena odświeżania do autoryzowania żądań bez ponownego wyświetlania prośby o autoryzację.

Jeśli użytkownik został już uwierzytelniony, aplikacja może pobrać token odświeżania z bazy danych i zapisać go w sesji po stronie serwera. Jeśli token odświeżania zostanie unieważniony lub będzie w inny sposób nieprawidłowy, musisz to wykryć i podjąć odpowiednie działania.

Korzystanie z danych logowania OAuth 2.0

Po pobraniu danych logowania OAuth 2.0 w sposób opisany w poprzedniej sekcji można ich użyć do autoryzacji obiektu usługi Gmail i wysyłania żądań do interfejsu API.

Tworzenie instancji obiektu usługi

Ten przykładowy kod pokazuje, jak utworzyć instancję obiektu usługi, a następnie autoryzować ją do wysyłania żądań do interfejsu 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)

Wysyłanie autoryzowanych żądań i sprawdzanie, czy dane logowania nie zostały cofnięte

Poniższy fragment kodu używa autoryzowanej instancji usługi Gmail do pobrania listy wiadomości.

Jeśli wystąpi błąd, kod sprawdza kod stanu HTTP 401, który powinien być obsługiwany przez przekierowanie użytkownika do adresu URL autoryzacji.

Więcej operacji interfejsu Gmail API znajdziesz w dokumentacji referencyjnej interfejsu API.

Python

from googleapiclient 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 = []
    if 'messages' in response:
      messages.extend(response['messages'])

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

    return messages
  except errors.HttpError as 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()

Dalsze kroki

Gdy będziesz mieć pewność, że możesz autoryzować żądania interfejsu Gmail API, możesz zacząć obsługiwać wiadomości, wątki i etykiety zgodnie z opisem w sekcjach przewodników dla programistów.

Więcej informacji o dostępnych metodach interfejsu API znajdziesz w dokumentacji API.