In [39]:
from oauth2client.client import OAuth2WebServerFlow
...
flow = OAuth2WebServerFlow(client_id='301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com',
                           client_secret='aPCX8YD0oYxpwYSiAeJ6qbTp',
                           scope='https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A93735856&start-date=2017-04-04&end-date=2017-04-20&metrics=ga%3Asessions&dimensions=ga%3Adate',
                           redirect_uri='http://example.com/auth_return')
flow


Out[39]:
<oauth2client.client.OAuth2WebServerFlow at 0x1b430536208>

In [29]:
import requests
from requests.auth import HTTPBasicAuth
r=requests.get('https://accounts.google.com/signin/oauth/oauthchooseaccount?client_id=407408718192.apps.googleusercontent.com&as=-74105678b2975efe&destination=https%3A%2F%2Fdevelopers.google.com&approval_state=!ChR4V3N1cjhJNU9HdndlZ3VmMXdLNhIfQTNkVzhyN1I4NkVjd0Q4c01wTnQ0WVpIRmFGNnZ4VQ%E2%88%99AE5-E40AAAAAWRW2YcSifloL0dHgVJS3MXeooGSDDwtV&xsrfsig=AHgIfE8-15qutuT11Hj4ewkBnfLnCICdUQ&flowName=GeneralOAuthFlow', auth=HTTPBasicAuth('mariana@skeingroup.com', 'M371216a'))
r.json()


---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-29-3964580eb522> in <module>()
      2 from requests.auth import HTTPBasicAuth
      3 r=requests.get('https://accounts.google.com/signin/oauth/oauthchooseaccount?client_id=407408718192.apps.googleusercontent.com&as=-74105678b2975efe&destination=https%3A%2F%2Fdevelopers.google.com&approval_state=!ChR4V3N1cjhJNU9HdndlZ3VmMXdLNhIfQTNkVzhyN1I4NkVjd0Q4c01wTnQ0WVpIRmFGNnZ4VQ%E2%88%99AE5-E40AAAAAWRW2YcSifloL0dHgVJS3MXeooGSDDwtV&xsrfsig=AHgIfE8-15qutuT11Hj4ewkBnfLnCICdUQ&flowName=GeneralOAuthFlow', auth=HTTPBasicAuth('mariana@skeingroup.com', 'M371216a'))
----> 4 r.json()

C:\Users\Analytics\Anaconda3\lib\site-packages\requests\models.py in json(self, **kwargs)
    848                     # used.
    849                     pass
--> 850         return complexjson.loads(self.text, **kwargs)
    851 
    852     @property

C:\Users\Analytics\Anaconda3\lib\site-packages\simplejson\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, use_decimal, **kw)
    514             parse_constant is None and object_pairs_hook is None
    515             and not use_decimal and not kw):
--> 516         return _default_decoder.decode(s)
    517     if cls is None:
    518         cls = JSONDecoder

C:\Users\Analytics\Anaconda3\lib\site-packages\simplejson\decoder.py in decode(self, s, _w, _PY3)
    372         if _PY3 and isinstance(s, binary_type):
    373             s = s.decode(self.encoding)
--> 374         obj, end = self.raw_decode(s)
    375         end = _w(s, end).end()
    376         if end != len(s):

C:\Users\Analytics\Anaconda3\lib\site-packages\simplejson\decoder.py in raw_decode(self, s, idx, _w, _PY3)
    402             elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf':
    403                 idx += 3
--> 404         return self.scan_once(s, idx=_w(s, idx).end())

JSONDecodeError: Expecting value: line 2 column 1 (char 1)

In [ ]:


In [38]:
from oauth2client.client import OAuth2Session

client_id = '301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com'
client_secret = 'aPCX8YD0oYxpwYSiAeJ6qbTp'
redirect_uri = 'https://your.callback/uri'

scope = ['https://www.googleapis.com/auth/userinfo.email',
             'https://www.googleapis.com/auth/userinfo.profile']
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri,
                          scope=scope)
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")

#print 'Please go to %s and authorize access.' % authorization_url 
authorization_response = raw_input('Enter the full callback URL')


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-38-5802085a0a57> in <module>()
----> 1 from oauth2client.client import OAuth2Session
      2 
      3 client_id = '301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com'
      4 client_secret = 'aPCX8YD0oYxpwYSiAeJ6qbTp'
      5 redirect_uri = 'https://your.callback/uri'

ImportError: cannot import name 'OAuth2Session'

In [36]:
r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
r


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-64e299b32ce2> in <module>()
----> 1 r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
      2 r

NameError: name 'oauth' is not defined

In [53]:
import requests
from requests_oauthlib import OAuth2Session

oauth = OAuth2Session(client_id='615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com',
                           client_secret='WMkLWDdkJ_hJu2LqgHze7lna',
                           scope='https://www.googleapis.com/auth/analytics',
                           redirect_uri='http://example.com/auth_return')


---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-53-e148fb60fd5a> in <module>()
      1 import requests
----> 2 from requests_oauthlib import OAuth2Session
      3 
      4 oauth = OAuth2Session(client_id='301497635683-49vo2tj7g3lj5rra1ureggsu7ok3jqk8.apps.googleusercontent.com',
      5                            client_secret='aPCX8YD0oYxpwYSiAeJ6qbTp',

ModuleNotFoundError: No module named 'requests_oauthlib'

In [45]:
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-45-09b81da45b59> in <module>()
----> 1 authorization_url, state = oauth.authorization_url(
      2         'https://accounts.google.com/o/oauth2/auth',
      3         # access_type and approval_prompt are Google specific extra
      4         # parameters.
      5         access_type="offline", approval_prompt="force")

AttributeError: 'OAuth2WebServerFlow' object has no attribute 'authorization_url'

In [42]:
token = oauth.fetch_token(
        'https://accounts.google.com/o/oauth2/token',
        authorization_response=authorization_response,
        client_secret=client_secret)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-42-2a16cf3a6ed2> in <module>()
----> 1 token = oauth.fetch_token(
      2         'https://accounts.google.com/o/oauth2/token',
      3         authorization_response=authorization_response,
      4         # Google specific extra parameter used for client
      5         # authentication

AttributeError: 'OAuth2WebServerFlow' object has no attribute 'fetch_token'

In [10]:
import requests

# Credentials you get from registering a new application
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
redirect_uri = 'http://app.skein.co'

# OAuth endpoints given in the Google API documentation
authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth"
token_url = "https://www.googleapis.com/oauth2/v4/token"
scope = [
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/analytics"
]

from requests_oauthlib import OAuth2Session
google = OAuth2Session(client_id, scope=scope, redirect_uri=redirect_uri)

# Redirect user to Google for authorization
authorization_url, state = google.authorization_url(authorization_base_url,
     # offline for refresh token
     # force to always make user click authorize
    access_type="offline", approval_prompt="force")
print('Please go here and authorize,', authorization_url)

# Fetch the access token
google.fetch_token(token_url, client_secret=client_secret,)

# Fetch a protected resource, i.e. user profile
r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
print(r.content)


Please go here and authorize, https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fapp.skein.co&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics&state=sga5UbmzAyH56hps4rMMLVTGjIyNR2&access_type=offline&approval_prompt=force
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-b953484b403b> in <module>()
     26 
     27 # Fetch the access token
---> 28 google.fetch_token(token_url, client_secret=client_secret,)
     29 
     30 # Fetch a protected resource, i.e. user profile

C:\Users\Analytics\Anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py in fetch_token(self, token_url, code, authorization_response, body, auth, username, password, method, timeout, headers, verify, proxies, **kwargs)
    190             code = self._client.code
    191             if not code:
--> 192                 raise ValueError('Please supply either code or '
    193                                  'authorization_response parameters.')
    194 

ValueError: Please supply either code or authorization_response parameters.

In [ ]:


In [11]:
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
redirect_uri = 'http://app.skein.co'

In [12]:
scope = ['https://www.googleapis.com/auth/userinfo.email',
             'https://www.googleapis.com/auth/userinfo.profile']
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri,
                          scope=scope)
authorization_url, state = oauth.authorization_url(
        'https://accounts.google.com/o/oauth2/auth',
        # access_type and approval_prompt are Google specific extra
        # parameters.
        access_type="offline", approval_prompt="force")

print('Please go to %s and authorize access.' % authorization_url)
authorization_response = raw_input('Enter the full callback URL')


Please go to https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Fapp.skein.co&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=6wJM8s5ir7kBHWMmORLvSpAOwdLOE7&access_type=offline&approval_prompt=force and authorize access.
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-baa5c4c03fac> in <module>()
     10 
     11 print('Please go to %s and authorize access.' % authorization_url)
---> 12 authorization_response = raw_input('Enter the full callback URL')

NameError: name 'raw_input' is not defined

In [23]:
import requests
from requests_oauthlib import OAuth1

url="https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A93735856&start-date=2017-04-04&end-date=2017-04-20&metrics=ga%3Asessions&dimensions=ga%3Adate" 
auth=OAuth1('615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com', 'WMkLWDdkJ_hJu2LqgHze7lna')

r = requests.get(url, auth=auth)

r.json()


Out[23]:
{'error': {'code': 401,
  'errors': [{'domain': 'global',
    'location': 'Authorization',
    'locationType': 'header',
    'message': 'Invalid Credentials',
    'reason': 'authError'}],
  'message': 'Invalid Credentials'}}

In [ ]:


In [30]:
client_id = '615971725291-80293f88sc1iknsg705loom9q4n0b8vq.apps.googleusercontent.com'
client_secret = 'WMkLWDdkJ_hJu2LqgHze7lna'
token = 'ya29.GltHBEer6RL1iLcOoFYk7Qb_xt8S_XUFZuHVbfio3iro0x9yAWHrMZwwrEHlvfv4g9ea0nBuwcsvcMxfIXEvz5g8UcIbyEjEPN7x8sBERQXvS8bhKdciYLFSZlOW'

In [31]:
from oauth2client import client, crypt

# (Receive token by HTTPS POST)


try:
    idinfo = client.verify_id_token(token, client_id)

    # Or, if multiple clients access the backend server:
    #idinfo = client.verify_id_token(token, None)
    #if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
    #    raise crypt.AppIdentityError("Unrecognized client.")

    if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
        raise crypt.AppIdentityError("Wrong issuer.")

    # If auth request is from a G Suite domain:
    #if idinfo['hd'] != GSUITE_DOMAIN_NAME:
    #    raise crypt.AppIdentityError("Wrong hosted domain.")
except crypt.AppIdentityError:
    # Invalid token
    userid = idinfo['sub']


---------------------------------------------------------------------------
AppIdentityError                          Traceback (most recent call last)
<ipython-input-31-142225f5a4e6> in <module>()
      6 try:
----> 7     idinfo = client.verify_id_token(token, client_id)
      8 

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\_helpers.py in positional_wrapper(*args, **kwargs)
    132                     logger.warning(message)
--> 133             return wrapped(*args, **kwargs)
    134         return positional_wrapper

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\client.py in verify_id_token(id_token, audience, http, cert_uri)
   1551         certs = json.loads(_helpers._from_bytes(content))
-> 1552         return crypt.verify_signed_jwt_with_certs(id_token, certs, audience)
   1553     else:

C:\Users\Analytics\Anaconda3\lib\site-packages\oauth2client\crypt.py in verify_signed_jwt_with_certs(jwt, certs, audience)
    227         raise AppIdentityError(
--> 228             'Wrong number of segments in token: {0}'.format(jwt))
    229 

AppIdentityError: Wrong number of segments in token: b'ya29.GltHBEer6RL1iLcOoFYk7Qb_xt8S_XUFZuHVbfio3iro0x9yAWHrMZwwrEHlvfv4g9ea0nBuwcsvcMxfIXEvz5g8UcIbyEjEPN7x8sBERQXvS8bhKdciYLFSZlOW'

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-31-142225f5a4e6> in <module>()
     20 except crypt.AppIdentityError:
     21     # Invalid token
---> 22     userid = idinfo['sub']

NameError: name 'idinfo' is not defined

In [ ]:


In [26]:
from oauthlib.oauth2 import BackendApplicationClient

client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url='https://accounts.google.com/o/oauth2/auth', client_id=client_id, client_secret=client_secret)


---------------------------------------------------------------------------
MissingTokenError                         Traceback (most recent call last)
<ipython-input-26-0462c6667e40> in <module>()
      2 client = BackendApplicationClient(client_id=client_id)
      3 oauth = OAuth2Session(client=client)
----> 4 token = oauth.fetch_token(token_url='https://accounts.google.com/o/oauth2/auth', client_id=client_id, client_secret=client_secret)

C:\Users\Analytics\Anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py in fetch_token(self, token_url, code, authorization_response, body, auth, username, password, method, timeout, headers, verify, proxies, **kwargs)
    242             r = hook(r)
    243 
--> 244         self._client.parse_request_body_response(r.text, scope=self.scope)
    245         self.token = self._client.token
    246         log.debug('Obtained token %s.', self.token)

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py in parse_request_body_response(self, body, scope, **kwargs)
    407         .. _`Section 7.1`: http://tools.ietf.org/html/rfc6749#section-7.1
    408         """
--> 409         self.token = parse_token_response(body, scope=scope)
    410         self._populate_attributes(self.token)
    411         return self.token

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py in parse_token_response(body, scope)
    374 
    375     params = OAuth2Token(params, old_scope=scope)
--> 376     validate_token_parameters(params)
    377     return params
    378 

C:\Users\Analytics\Anaconda3\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py in validate_token_parameters(params)
    384 
    385     if not 'access_token' in params:
--> 386         raise MissingTokenError(description="Missing access token parameter.")
    387 
    388     if not 'token_type' in params:

MissingTokenError: (missing_token) Missing access token parameter.