DCM API: Handling OAuth2.0 Authentification in Python

1,101 views
Skip to first unread message

Tobias Orzegowski

unread,
Apr 23, 2018, 4:48:04 PM4/23/18
to Google's DoubleClick Campaign Manager API Forum
Hi all,

we are trying to implement the OAuth2.0 Authentification using Pyhton 2.7.
Offline Access is needed because we are using a web application where the user is not present.

We've created a OAuth2.0 Client ID incl. the correspoding secret json file.

Now we're trying to implement the needed Python Script according to the examples found here:

As a returned value we will need to have the Refresh Token back.
We are still beginners in Python Code. Could you please have a look at the Code we've generated so far.
For us it's not 100 % clear how the Code is interpreted (e.g. what does @app.route mean).

Do you have any working example for the OAuth2.0 Authentification in combination with the DCM API using Python?

Thanks a lot and kind regards
Tobias


import os
import flask
import requests

import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery

# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/dfareporting']
API_SERVICE_NAME = 'dfareporting'
API_VERSION = 'v3.0'

app = flask.Flask(__name__)
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See http://flask.pocoo.org/docs/0.12/quickstart/#sessions.
app.secret_key = 'xxx'


@app.route('/test')
def test_api_request():
if 'credentials' not in flask.session:
return flask.redirect('authorize')

# Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials'])

drive = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)

files = drive.files().list().execute()

# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
flask.session['credentials'] = credentials_to_dict(credentials)

return flask.jsonify(**files)
#CREDENTIAL_STORE_FILE = API_NAME + '.dat'
#return flask.jsonify(**CREDENTIAL_STORE_FILE)

@app.route('/authorize')
def authorize():
# Create flow instance to manage the OAuth 2.0 Authorization Grant Flow steps.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES)

flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')

# Store the state so the callback can verify the auth server response.
flask.session['state'] = state

return flask.redirect(authorization_url)


@app.route('/oauth2callback')
def oauth2callback():
# Specify the state when creating the flow in the callback so that it can
# verified in the authorization server response.
state = flask.session['state']

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

# Use the authorization server's response to fetch the OAuth 2.0 tokens.
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)

# Store credentials in the session.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials)

return flask.redirect(flask.url_for('test_api_request'))


def credentials_to_dict(credentials):
return {'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes}




if __name__ == '__main__':
# When running locally, disable OAuthlib's HTTPs verification.
# ACTION ITEM for developers:
# When running in production *do not* leave this option enabled.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

# Specify a hostname and port that are set as a valid redirect URI
# for your API project in the Google API Console.
app.run('localhost', 8080, debug=True)

Lakshmi Prathipati (DCM API Team)

unread,
Apr 24, 2018, 3:09:19 PM4/24/18
to Google's DoubleClick Campaign Manager API Forum
Hi,

I responded to you on the other thread. The browser setup is needed only once and you can do that outside the production environment. We do have GitHub samples where the OAuth steps will be handled smoothly. But the python sample is for the application type other. Even for this sample you need to go through the one step authorization on the browser.

Thanks,
Lakshmi, DCM API Team


sochirca ilie

unread,
Jul 26, 2018, 4:05:22 PM7/26/18
to Google's DoubleClick Campaign Manager API Forum
Hi Tobias, 

Did you succeed to find out a correct example explaining how google oauth2 is working? can you please help me with one?

Thanks a lot!

Lakshmi Prathipati (DCM API Team)

unread,
Jul 27, 2018, 3:03:43 PM7/27/18
to Google's DoubleClick Campaign Manager API Forum
Hi,

Please find the OAuth details from here.The Google APIs client libraries can handle some of the authorization process for you. You might want to go through this authorize request document as well.


Thanks,
Lakshmi, DCM API Team

sochirca ilie

unread,
Jul 30, 2018, 2:21:05 AM7/30/18
to google-doubleclick-...@googlegroups.com
Thank you very much for your help!

--
You received this message because you are subscribed to the Google Groups "Google's DoubleClick Campaign Manager API Forum" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-doubleclick-for-ad...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tobias Orzegowski

unread,
Jul 30, 2018, 4:29:58 AM7/30/18
to google-doubleclick-...@googlegroups.com
Hi,

using the official GitHub Example (https://github.com/googleads/googleads-dfa-reporting-samples) is working without any Problems for us.

Cheers
Tobias

Reply all
Reply to author
Forward
0 new messages