सर्वर साइड ऑथराइज़ेशन लागू करें

Gmail API को किए जाने वाले अनुरोधों को अनुमति देने के लिए, OAuth 2.0 क्रेडेंशियल का इस्तेमाल किया जाना चाहिए. जब आपके ऐप्लिकेशन को उपयोगकर्ता की ओर से Google API को ऐक्सेस करने की ज़रूरत हो, तब आपको सर्वर साइड फ़्लो का इस्तेमाल करना चाहिए. उदाहरण के लिए, जब उपयोगकर्ता ऑफ़लाइन हो. इस तरीके के लिए आपके क्लाइंट से आपके सर्वर पर एक बार इस्तेमाल होने वाला ऑथराइज़ेशन कोड पास करना ज़रूरी है; इस कोड का इस्तेमाल ऐक्सेस टोकन पाने और आपके सर्वर के लिए टोकन रीफ़्रेश करने के लिए किया जाता है.

सर्वर साइड Google OAuth 2.0 लागू करने के बारे में ज़्यादा जानने के लिए, वेब सर्वर ऐप्लिकेशन के लिए OAuth 2.0 का इस्तेमाल करना देखें.

विषय सूची

क्लाइंट आईडी और क्लाइंट सीक्रेट बनाना

Gmail API का इस्तेमाल शुरू करने के लिए, आपको सबसे पहले सेटअप टूल का इस्तेमाल करना होगा. यह आपको Google API Console में प्रोजेक्ट बनाने, एपीआई की सुविधा चालू करने, और क्रेडेंशियल बनाने के बारे में जानकारी देता है.

  1. अपने OAuth 2.0 क्रेडेंशियल बनाने के लिए, क्रेडेंशियल पेज पर जाकर, क्रेडेंशियल बनाएं > OAuth क्लाइंट आईडी पर क्लिक करें या सेवा खाता बनाने के लिए, क्रेडेंशियल बनाएं > सेवा खाता कुंजी पर क्लिक करें.
  2. अगर आपने OAuth क्लाइंट आईडी बनाया है, तो यह चुनें कि आपका ऐप्लिकेशन किस तरह का है.
  3. फ़ॉर्म भरें और बनाएं पर क्लिक करें.

आपके ऐप्लिकेशन के क्लाइंट आईडी और सेवा खाते की कुंजियां अब क्रेडेंशियल पेज पर सूची में शामिल हैं. ज़्यादा जानकारी के लिए, किसी क्लाइंट आईडी पर क्लिक करें. आईडी के टाइप के आधार पर पैरामीटर अलग-अलग होते हैं. हालांकि, इनमें ईमेल पता, क्लाइंट सीक्रेट, JavaScript ऑरिजिन या रीडायरेक्ट यूआरआई शामिल हो सकते हैं.

Client-ID का ध्यान रखें, क्योंकि आपको इसे बाद में अपने कोड में जोड़ना होगा.

अनुमति के अनुरोधों पर काम करना

जब कोई उपयोगकर्ता पहली बार आपका ऐप्लिकेशन लोड करता है, तो उसे एक डायलॉग दिखाया जाता है, जिसमें आपके ऐप्लिकेशन को अनुरोध की गई अनुमति के दायरे के साथ अपने Gmail खाते को ऐक्सेस करने की अनुमति देने के लिए, एक डायलॉग दिखाया जाता है. इस शुरुआती अनुमति के बाद, उपयोगकर्ता को अनुमति वाला डायलॉग सिर्फ़ तब दिखाया जाता है, जब आपके ऐप्लिकेशन का क्लाइंट आईडी बदलता हो या अनुरोध किए गए दायरे बदल गए हों.

उपयोगकर्ता की पुष्टि करें

इस शुरुआती साइन इन से, अनुमति देने वाले नतीजे का ऑब्जेक्ट दिखता है. इसमें ऑथराइज़ेशन कोड शामिल होता है.

ऐक्सेस टोकन के लिए ऑथराइज़ेशन कोड को एक्सचेंज करना

ऑथराइज़ेशन कोड एक बार इस्तेमाल होने वाला कोड होता है. आपका सर्वर इसे ऐक्सेस टोकन के लिए बदल सकता है. यह ऐक्सेस टोकन 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 सेवा से जुड़े ऑब्जेक्ट को अनुमति देने और एपीआई को अनुरोध भेजने के लिए किया जा सकता है.

सर्विस ऑब्जेक्ट को इंस्टैंशिएट करें

यह कोड सैंपल, किसी सर्विस ऑब्जेक्ट को इंस्टैंशिएट करने और उसे एपीआई अनुरोध करने की अनुमति देने का तरीका बताता है.

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 सेवा इंस्टेंस का इस्तेमाल करता है.

अगर कोई गड़बड़ी होती है, तो कोड एक एचटीटीपी 401 स्टेटस कोड की जांच करता है. इसे इस्तेमाल करने वाले को अनुमति देने वाले यूआरएल पर रीडायरेक्ट करके मैनेज किया जाना चाहिए.

Gmail 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 अनुरोधों को अनुमति देने के लिए तैयार हों, तब डेवलपर गाइड सेक्शन में बताए गए तरीके से मैसेज, थ्रेड, और लेबल मैनेज करना शुरू किया जा सकता है.

एपीआई के उपलब्ध तरीकों के बारे में ज़्यादा जानने के लिए, एपीआई का रेफ़रंस देखें.