oauth2_google.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2012 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Performs client tasks for testing IMAP OAuth2 authentication.
  17. To use this script, you'll need to have registered with Google as an OAuth
  18. application and obtained an OAuth client ID and client secret.
  19. See https://developers.google.com/identity/protocols/OAuth2 for instructions on
  20. registering and for documentation of the APIs invoked by this code.
  21. This script has 3 modes of operation.
  22. 1. The first mode is used to generate and authorize an OAuth2 token, the
  23. first step in logging in via OAuth2.
  24. oauth2 --user=xxx@gmail.com \
  25. --client_id=1038[...].apps.googleusercontent.com \
  26. --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \
  27. --generate_oauth2_token
  28. The script will converse with Google and generate an oauth request
  29. token, then present you with a URL you should visit in your browser to
  30. authorize the token. Once you get the verification code from the Google
  31. website, enter it into the script to get your OAuth access token. The output
  32. from this command will contain the access token, a refresh token, and some
  33. metadata about the tokens. The access token can be used until it expires, and
  34. the refresh token lasts indefinitely, so you should record these values for
  35. reuse.
  36. 2. The script will generate new access tokens using a refresh token.
  37. oauth2 --user=xxx@gmail.com \
  38. --client_id=1038[...].apps.googleusercontent.com \
  39. --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \
  40. --refresh_token=1/Yzm6MRy4q1xi7Dx2DuWXNgT6s37OrP_DW_IoyTum4YA
  41. 3. The script will generate an OAuth2 string that can be fed
  42. directly to IMAP or SMTP. This is triggered with the --generate_oauth2_string
  43. option.
  44. oauth2 --generate_oauth2_string --user=xxx@gmail.com \
  45. --access_token=ya29.AGy[...]ezLg
  46. The output of this mode will be a base64-encoded string. To use it, connect to a
  47. IMAPFE and pass it as the second argument to the AUTHENTICATE command.
  48. a AUTHENTICATE XOAUTH2 a9sha9sfs[...]9dfja929dk==
  49. """
  50. import base64
  51. import imaplib
  52. import json
  53. from optparse import OptionParser
  54. import smtplib
  55. import sys
  56. import urllib
  57. def SetupOptionParser():
  58. # Usage message is the module's docstring.
  59. parser = OptionParser(usage=__doc__)
  60. parser.add_option('--generate_oauth2_token',
  61. action='store_true',
  62. dest='generate_oauth2_token',
  63. help='generates an OAuth2 token for testing')
  64. parser.add_option('--generate_oauth2_string',
  65. action='store_true',
  66. dest='generate_oauth2_string',
  67. help='generates an initial client response string for '
  68. 'OAuth2')
  69. parser.add_option('--client_id',
  70. default=None,
  71. help='Client ID of the application that is authenticating. '
  72. 'See OAuth2 documentation for details.')
  73. parser.add_option('--client_secret',
  74. default=None,
  75. help='Client secret of the application that is '
  76. 'authenticating. See OAuth2 documentation for '
  77. 'details.')
  78. parser.add_option('--access_token',
  79. default=None,
  80. help='OAuth2 access token')
  81. parser.add_option('--refresh_token',
  82. default=None,
  83. help='OAuth2 refresh token')
  84. parser.add_option('--scope',
  85. default='https://mail.google.com/',
  86. help='scope for the access token. Multiple scopes can be '
  87. 'listed separated by spaces with the whole argument '
  88. 'quoted.')
  89. parser.add_option('--test_imap_authentication',
  90. action='store_true',
  91. dest='test_imap_authentication',
  92. help='attempts to authenticate to IMAP')
  93. parser.add_option('--test_smtp_authentication',
  94. action='store_true',
  95. dest='test_smtp_authentication',
  96. help='attempts to authenticate to SMTP')
  97. parser.add_option('--user',
  98. default=None,
  99. help='email address of user whose account is being '
  100. 'accessed')
  101. parser.add_option('--quiet',
  102. action='store_true',
  103. default=False,
  104. dest='quiet',
  105. help='Omit verbose descriptions and only print '
  106. 'machine-readable outputs.')
  107. return parser
  108. # The URL root for accessing Google Accounts.
  109. GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com'
  110. # Hardcoded dummy redirect URI for non-web apps.
  111. REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
  112. def AccountsUrl(command):
  113. """Generates the Google Accounts URL.
  114. Args:
  115. command: The command to execute.
  116. Returns:
  117. A URL for the given command.
  118. """
  119. return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command)
  120. def UrlEscape(text):
  121. # See OAUTH 5.1 for a definition of which characters need to be escaped.
  122. return urllib.quote(text, safe='~-._')
  123. def UrlUnescape(text):
  124. # See OAUTH 5.1 for a definition of which characters need to be escaped.
  125. return urllib.unquote(text)
  126. def FormatUrlParams(params):
  127. """Formats parameters into a URL query string.
  128. Args:
  129. params: A key-value map.
  130. Returns:
  131. A URL query string version of the given parameters.
  132. """
  133. param_fragments = []
  134. for param in sorted(params.iteritems(), key=lambda x: x[0]):
  135. param_fragments.append('%s=%s' % (param[0], UrlEscape(param[1])))
  136. return '&'.join(param_fragments)
  137. def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'):
  138. """Generates the URL for authorizing access.
  139. This uses the "OAuth2 for Installed Applications" flow described at
  140. https://developers.google.com/accounts/docs/OAuth2InstalledApp
  141. Args:
  142. client_id: Client ID obtained by registering your app.
  143. scope: scope for access token, e.g. 'https://mail.google.com'
  144. Returns:
  145. A URL that the user should visit in their browser.
  146. """
  147. params = {}
  148. params['client_id'] = client_id
  149. params['redirect_uri'] = REDIRECT_URI
  150. params['scope'] = scope
  151. params['response_type'] = 'code'
  152. return '%s?%s' % (AccountsUrl('o/oauth2/auth'),
  153. FormatUrlParams(params))
  154. def AuthorizeTokens(client_id, client_secret, authorization_code):
  155. """Obtains OAuth access token and refresh token.
  156. This uses the application portion of the "OAuth2 for Installed Applications"
  157. flow at https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse
  158. Args:
  159. client_id: Client ID obtained by registering your app.
  160. client_secret: Client secret obtained by registering your app.
  161. authorization_code: code generated by Google Accounts after user grants
  162. permission.
  163. Returns:
  164. The decoded response from the Google Accounts server, as a dict. Expected
  165. fields include 'access_token', 'expires_in', and 'refresh_token'.
  166. """
  167. params = {}
  168. params['client_id'] = client_id
  169. params['client_secret'] = client_secret
  170. params['code'] = authorization_code
  171. params['redirect_uri'] = REDIRECT_URI
  172. params['grant_type'] = 'authorization_code'
  173. request_url = AccountsUrl('o/oauth2/token')
  174. response = urllib.urlopen(request_url, urllib.urlencode(params)).read()
  175. return json.loads(response)
  176. def RefreshToken(client_id, client_secret, refresh_token):
  177. """Obtains a new token given a refresh token.
  178. See https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh
  179. Args:
  180. client_id: Client ID obtained by registering your app.
  181. client_secret: Client secret obtained by registering your app.
  182. refresh_token: A previously-obtained refresh token.
  183. Returns:
  184. The decoded response from the Google Accounts server, as a dict. Expected
  185. fields include 'access_token', 'expires_in', and 'refresh_token'.
  186. """
  187. params = {}
  188. params['client_id'] = client_id
  189. params['client_secret'] = client_secret
  190. params['refresh_token'] = refresh_token
  191. params['grant_type'] = 'refresh_token'
  192. request_url = AccountsUrl('o/oauth2/token')
  193. response = urllib.urlopen(request_url, urllib.urlencode(params)).read()
  194. return json.loads(response)
  195. def GenerateOAuth2String(username, access_token, base64_encode=True):
  196. """Generates an IMAP OAuth2 authentication string.
  197. See https://developers.google.com/google-apps/gmail/oauth2_overview
  198. Args:
  199. username: the username (email address) of the account to authenticate
  200. access_token: An OAuth2 access token.
  201. base64_encode: Whether to base64-encode the output.
  202. Returns:
  203. The SASL argument for the OAuth2 mechanism.
  204. """
  205. auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token)
  206. if base64_encode:
  207. auth_string = base64.b64encode(auth_string)
  208. return auth_string
  209. def TestImapAuthentication(user, auth_string):
  210. """Authenticates to IMAP with the given auth_string.
  211. Prints a debug trace of the attempted IMAP connection.
  212. Args:
  213. user: The Gmail username (full email address)
  214. auth_string: A valid OAuth2 string, as returned by GenerateOAuth2String.
  215. Must not be base64-encoded, since imaplib does its own base64-encoding.
  216. """
  217. print
  218. imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
  219. imap_conn.debug = 4
  220. imap_conn.authenticate('XOAUTH2', lambda x: auth_string)
  221. imap_conn.select('INBOX')
  222. def TestSmtpAuthentication(user, auth_string):
  223. """Authenticates to SMTP with the given auth_string.
  224. Args:
  225. user: The Gmail username (full email address)
  226. auth_string: A valid OAuth2 string, not base64-encoded, as returned by
  227. GenerateOAuth2String.
  228. """
  229. print
  230. smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
  231. smtp_conn.set_debuglevel(True)
  232. smtp_conn.ehlo('test')
  233. smtp_conn.starttls()
  234. smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
  235. def RequireOptions(options, *args):
  236. missing = [arg for arg in args if getattr(options, arg) is None]
  237. if missing:
  238. print 'Missing options: %s' % ' '.join(missing)
  239. sys.exit(-1)
  240. def main(argv):
  241. options_parser = SetupOptionParser()
  242. (options, args) = options_parser.parse_args()
  243. if options.refresh_token:
  244. RequireOptions(options, 'client_id', 'client_secret')
  245. response = RefreshToken(options.client_id, options.client_secret,
  246. options.refresh_token)
  247. if options.quiet:
  248. print response['access_token']
  249. else:
  250. print 'Access Token: %s' % response['access_token']
  251. print 'Access Token Expiration Seconds: %s' % response['expires_in']
  252. elif options.generate_oauth2_string:
  253. RequireOptions(options, 'user', 'access_token')
  254. oauth2_string = GenerateOAuth2String(options.user, options.access_token)
  255. if options.quiet:
  256. print oauth2_string
  257. else:
  258. print 'OAuth2 argument:\n' + oauth2_string
  259. elif options.generate_oauth2_token:
  260. RequireOptions(options, 'client_id', 'client_secret')
  261. print 'To authorize token, visit this url and follow the directions:'
  262. print ' %s' % GeneratePermissionUrl(options.client_id, options.scope)
  263. authorization_code = raw_input('Enter verification code: ')
  264. response = AuthorizeTokens(options.client_id, options.client_secret,
  265. authorization_code)
  266. print 'Refresh Token: %s' % response['refresh_token']
  267. print 'Access Token: %s' % response['access_token']
  268. print 'Access Token Expiration Seconds: %s' % response['expires_in']
  269. elif options.test_imap_authentication:
  270. RequireOptions(options, 'user', 'access_token')
  271. TestImapAuthentication(options.user,
  272. GenerateOAuth2String(options.user, options.access_token,
  273. base64_encode=False))
  274. elif options.test_smtp_authentication:
  275. RequireOptions(options, 'user', 'access_token')
  276. TestSmtpAuthentication(options.user,
  277. GenerateOAuth2String(options.user, options.access_token,
  278. base64_encode=False))
  279. else:
  280. options_parser.print_help()
  281. print 'Nothing to do, exiting.'
  282. return
  283. if __name__ == '__main__':
  284. main(sys.argv)