Implementare l'autorizzazione lato server

Le richieste all'API Gmail devono essere autorizzate utilizzando le credenziali OAuth 2.0. Devi utilizzare il flusso lato server quando la tua applicazione deve accedere alle API di Google per conto dell'utente, ad esempio quando l'utente è offline. Questo approccio richiede il passaggio di un codice di autorizzazione una tantum dal client al server; questo codice viene utilizzato per acquisire un token di accesso e token di aggiornamento per il server.

Per saperne di più sull'implementazione di Google OAuth 2.0 lato server, consulta Utilizzo di OAuth 2.0 per applicazioni server web.

Sommario

Creare un ID client e un client secret

Per iniziare a utilizzare l'API Gmail, devi prima utilizzare lo strumento di configurazione, che ti guida nella creazione di un progetto nella console API di Google, nell'abilitazione dell'API e nella creazione delle credenziali.

  1. Nella pagina Credenziali, fai clic su Crea credenziali > ID client OAuth per creare le tue credenziali OAuth 2.0 o su Crea credenziali > Chiave dell'account di servizio per creare un account di servizio.
  2. Se hai creato un ID client OAuth, seleziona il tipo di applicazione.
  3. Compila il modulo e fai clic su Crea.

Gli ID client e le chiavi dell'account di servizio dell'applicazione sono ora elencati nella pagina Credenziali. Per maggiori dettagli, fai clic su un ID client. I parametri variano in base al tipo di ID, ma potrebbero includere indirizzo email, client secret, origini JavaScript o URI di reindirizzamento.

Prendi nota dell'ID client perché dovrai aggiungerlo al codice in un secondo momento.

Gestione delle richieste di autorizzazione

Quando un utente carica la tua applicazione per la prima volta, viene visualizzata una finestra di dialogo per concedere all'applicazione l'autorizzazione ad accedere al proprio account Gmail con gli ambiti di autorizzazione richiesti. Dopo questa autorizzazione iniziale, all'utente viene presentata la finestra di dialogo dell'autorizzazione solo se l'ID client dell'app cambia o se gli ambiti richiesti sono cambiati.

Autenticare l'utente

Questo accesso iniziale restituisce un oggetto del risultato dell'autorizzazione che contiene un codice di autorizzazione, in caso di esito positivo.

Scambia il codice di autorizzazione con un token di accesso

Il codice di autorizzazione è un codice monouso che il tuo server può scambiare con un token di accesso. Questo token di accesso viene trasmesso all'API Gmail per concedere all'applicazione l'accesso ai dati utente per un periodo di tempo limitato.

Se l'applicazione richiede l'accesso a offline, la prima volta che l'app scambia il codice di autorizzazione, riceve anche un token di aggiornamento che utilizza per ricevere un nuovo token di accesso dopo la scadenza di un token precedente. L'applicazione archivia questo token di aggiornamento (di solito in un database sul tuo server) per un utilizzo successivo.

I seguenti esempi di codice mostrano lo scambio di un codice di autorizzazione con un token di accesso con accesso a offline e l'archiviazione del token di aggiornamento.

Python

Sostituisci il valore CLIENTSECRETS_LOCATION con la posizione del file 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)

Autorizzazione con credenziali archiviate

Quando gli utenti visitano la tua app dopo la prima autorizzazione, l'applicazione può utilizzare un token di aggiornamento archiviato per autorizzare le richieste senza chiedere nuovamente l'autorizzazione all'utente.

Se hai già autenticato l'utente, l'applicazione può recuperare il token di aggiornamento dal suo database e archiviarlo in una sessione lato server. Se il token di aggiornamento viene revocato o non è comunque valido, dovrai individuarlo e intraprendere le azioni appropriate.

Utilizzo delle credenziali OAuth 2.0

Una volta recuperate le credenziali OAuth 2.0 come mostrato nella sezione precedente, possono essere utilizzate per autorizzare un oggetto del servizio Gmail e inviare richieste all'API.

Crea l'istanza di un oggetto di servizio

Questo esempio di codice mostra come creare un'istanza di un oggetto di servizio e autorizzarlo a effettuare richieste 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)

Invia le richieste autorizzate e verifica se sono presenti credenziali revocate

Lo snippet di codice riportato di seguito utilizza un'istanza di servizio Gmail autorizzata per recuperare un elenco di messaggi.

Se si verifica un errore, il codice verifica la presenza di un codice di stato HTTP 401, che deve essere gestito reindirizzando l'utente all'URL di autorizzazione.

Altre operazioni dell'API Gmail sono documentate nel riferimento 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()

Passaggi successivi

Una volta acquisita dimestichezza con l'autorizzazione delle richieste API Gmail, potrai iniziare a gestire messaggi, thread ed etichette, come descritto nelle sezioni delle guide per gli sviluppatori.

Per saperne di più sui metodi API disponibili, consulta la documentazione di riferimento API.